package com.syni.mdd.yhd.common.all.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.yhd.common.all.config.pay.wxPay.WxPayBeanFactory;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.controller.pay.aliPay.AliPayController;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsDxGroupBuyDao;
import com.syni.mdd.yhd.common.all.dto.reponseDto.BmsBusinessRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.config.GoldRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.BusinessRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.GroupContentRpDto;
import com.syni.mdd.yhd.common.all.dto.requestDto.groupBuy.DxGroupBuyReDto;
import com.syni.mdd.yhd.common.all.dto.requestDto.groupBuy.GrSubFood;
import com.syni.mdd.yhd.common.all.dto.requestDto.groupBuy.GroupBuyUseReDto;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.bo.groupBuy.GroupBuyConditionHolder;
import com.syni.mdd.yhd.common.all.entity.config.BmsDxConfig;
import com.syni.mdd.yhd.common.all.entity.bo.user.CheckUserBo;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsUserReceCoupon;
import com.syni.mdd.yhd.common.all.entity.record.ReGroupUseLog;
import com.syni.mdd.yhd.common.all.entity.record.ReTransferLog;
import com.syni.mdd.yhd.common.all.enums.business.CouponEnums;
import com.syni.mdd.yhd.common.all.listen.groupBuy.GetGroupBuyDetailEvent;
import com.syni.mdd.yhd.common.all.listen.groupBuy.GroupBuyEvent;
import com.syni.mdd.yhd.common.all.listen.userRece.UserReceEvent;
import com.syni.mdd.yhd.common.all.listen.video.VideoEvent;
import com.syni.mdd.yhd.common.all.quartz.QuartzDo;
import com.syni.mdd.yhd.common.all.quartz.groupBuy.job.LimitGroupBuyTimingJob;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.groupBuy.BmsDxGroupBuyRecordService;
import com.syni.mdd.yhd.common.all.service.pay.wxPay.WxPayService;
import com.syni.mdd.yhd.common.all.service.record.ReTransferLogService;
import com.syni.mdd.yhd.common.all.service.search.BmsSearchService;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.sjb.common.component.utils.common.utils.ArithUtil;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.yhd.common.all.utils.LocationUtils;
import com.syni.mdd.yhd.common.all.utils.RequestParamUtils;
import com.syni.mdd.yhd.common.all.utils.RestTemplateUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.yhd.common.all.utils.WebUtils;
import com.syni.mdd.yhd.common.all.utils.auth.JwtTokenAuth;
import com.syni.mdd.yhd.common.all.vo.rp.config.GoldRpVo;
import com.syni.mdd.yhd.common.all.vo.rp.groupBuy.GetAllGroupBuy_v2Vo;
import com.syni.mdd.yhd.common.all.vo.rp.groupBuy.GetMerchantGroupBuyDetailRpVo;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiCoupon.SearchCouponDetailDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiCoupon.SearchCouponDetailDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddDistSys.VerifyCodeDto;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddDistSys.FxCenterService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @className
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
public class BmsDxGroupBuyServiceImpl extends BaseService<BmsDxGroupBuy,Integer> implements BmsDxGroupBuyService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private static final Map<Integer,Integer> FRONT_TEMPATE_MAP = new HashMap<>();

    static {
        //美食模板
        FRONT_TEMPATE_MAP.put(Constants.GROUP_BUY_FOOD_TEMP,Constants.FOOD_TEMPLATE);
        FRONT_TEMPATE_MAP.put(Constants.GROUP_BUY_FOOD_SECOND_TEMP,Constants.FOOD_TEMPLATE);
        FRONT_TEMPATE_MAP.put(Constants.GROUP_BUY_FOOD_BARGAIN_TEMP,Constants.FOOD_TEMPLATE);
        FRONT_TEMPATE_MAP.put(Constants.GROUP_BUY_FOOD_NO_SECOND_TEMP,Constants.FOOD_TEMPLATE);

        //海报模板
        FRONT_TEMPATE_MAP.put(Constants.GROUP_BUY_PEI_XUN_TEMP,Constants.POSTER_TEMPLATE);
        //富文本
        FRONT_TEMPATE_MAP.put(Constants.GROUP_BUY_GEN_RICH_TEMP,Constants.RICH_TEXT_TEMPLATE);
        FRONT_TEMPATE_MAP.put(Constants.GROUP_BUY_SECOND_RICH_TEMP,Constants.RICH_TEXT_TEMPLATE);
        FRONT_TEMPATE_MAP.put(Constants.GROUP_BUY_BARGAIN_RICH_TEMP,Constants.RICH_TEXT_TEMPLATE);
    }

    @Autowired
    EntityManager entityManager;

    @Autowired
    BmsDxGroupBuyDao bmsDxGroupBuyDao;

    @Autowired
    BmsDxFoodLibraryService bmsDxFoodLibraryService;

    @Autowired
    BmsDxSubFoodService bmsDxSubFoodService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsUserBusinessService bmsUserBusinessService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsDxOrderStatusService bmsDxOrderStatusService;

    @Autowired
    BmsDxGroupBuyUseService bmsDxGroupBuyUseService;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Autowired
    BmsBusinessinfoService bmsBusinessinfoService;

    @Autowired
    ReOrderLogService reOrderLogService;

    @Autowired
    ReGroupUseLogService reGroupUseLogService;

    @Autowired
    ReTransferLogService reTransferLogService;

    @Autowired
    AliPayController aliPayController;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Autowired
    BmsUserBusinessAuthService bmsUserBusinessAuthService;

    @Autowired
    BmsDxCouponService bmsDxCouponService;

    @Autowired
    BmsBusinessCouponService bmsBusinessCouponService;

    @Autowired
    BmsUserReceCouponService bmsUserReceCouponService;

    @Autowired
    BmsBusinessLabelService bmsBusinessLabelService;

    @Autowired
    BmsBusinessTypeRelationService bmsBusinessTypeRelationService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BmsVerRecordService bmsVerRecordService;

    @Autowired
    BmsCommonService bmsCommonService;

    @Autowired
    BmsBusinessAreaService bmsBusinessAreaService;

    @Autowired
    BmsDxGroupBuyRecordService bmsDxGroupBuyRecordService;

    @Autowired
    BmsDxConfigService bmsDxConfigService;

    @Autowired
    BmsSearchService bmsSearchService;

    @Autowired
    FxCenterService fxCenterService;

    @Autowired
    ImgPrefixService imgPrefixService;

    @Autowired
    WxPayService wxPayService;

    @Override
    public BmsDxGroupBuyDao getBaseDao() {
        return bmsDxGroupBuyDao;
    }

    @Override
    @Transactional
    public Map<String, Object> businessCreateGroupBuy(DxGroupBuyReDto dxGroupBuyReDto) {
        //处理图片大小图
        pushGrouPhotos(dxGroupBuyReDto);
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(Integer.parseInt(dxGroupBuyReDto.getUserId()),dxGroupBuyReDto.getBusinessId());
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        //查看商家是否绑定支付宝
        if(!bmsBusinessinfoService.checkBusinessHavingPayInfo(dxGroupBuyReDto.getBusinessId())){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_110,ResultMsg.CODE_ERROR_110);
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        if(dxGroupBuyReDto.getGroupTemplateId() == foodTemplateId
                || dxGroupBuyReDto.getGroupTemplateId() == beautyTemplate) {
            //处理初始值
            postHandleArgInit(dxGroupBuyReDto);
            //处理套餐内容
            dxGroupBuyReDto.setGroupContent(JSON.toJSONString(dxGroupBuyReDto.getGroupContentArg()));
            //处理可用时间
            Integer useWay =  dxGroupBuyReDto.getUseTimeArg().getUseWay();
            if (useWay == null) {
                return ResultMapHelper.result(ResultCode.CODE_ERROR_03, "使用时间不明确");
            }
            dxGroupBuyReDto.setUseWay(useWay);
            if (useWay == Constants.USE_IN_DAY) {
                dxGroupBuyReDto.setUseTime(Constants.USE_IN_DAY_DES);
            } else if (useWay == Constants.USE_IN_DAY_PART) {
                dxGroupBuyReDto.setUseTime(StringUtils.join(dxGroupBuyReDto.getUseTimeArg().getUseTime(), ","));
            }else if(useWay == Constants.USE_IN_DAY_BUS_HOUR){
                dxGroupBuyReDto.setUseTime("营业时间可用");
            }
            //处理有效期
            Integer expireWay = dxGroupBuyReDto.getExpireTimeArg().getExpireWay();
            if (expireWay == null) {
                return ResultMapHelper.result(ResultCode.CODE_ERROR_03, "使用时间不明确");
            }
            if (expireWay == Constants.EXPIRE_IN_MONTH) {
                dxGroupBuyReDto.setExpireMonth(dxGroupBuyReDto.getExpireTimeArg().getCustomExpireTime());
            } else if (expireWay == Constants.EXPIRE_IN_COS_DATE) {
                dxGroupBuyReDto.setExpireTime(DateTimeUtils.converStringToDate(dxGroupBuyReDto.getExpireTimeArg().getCustomExpireTime()));
            }
        }else if(dxGroupBuyReDto.getGroupTemplateId() == trainingTemplateId){
            if(dxGroupBuyReDto.getExpireTimeArg() != null) {
                Integer expireWay = dxGroupBuyReDto.getExpireTimeArg().getExpireWay();
                if(expireWay != null) {
                    if (expireWay == Constants.EXPIRE_IN_MONTH) {
                        dxGroupBuyReDto.setExpireMonth(dxGroupBuyReDto.getExpireTimeArg().getCustomExpireTime());
                    } else if (expireWay == Constants.EXPIRE_IN_COS_DATE) {
                        dxGroupBuyReDto.setExpireTime(DateTimeUtils.converStringToDate(dxGroupBuyReDto.getExpireTimeArg().getCustomExpireTime()));
                    }
                }
            }
        }
        BmsDxGroupBuy bmsDxGroupBuy = new BmsDxGroupBuy();
        BeanUtils.copyProperties(dxGroupBuyReDto,bmsDxGroupBuy,BeanUtils.getNullPropertyNames(dxGroupBuyReDto));
        bmsDxGroupBuy.setBusinessName(business.getVendorName());
        if(StringUtils.isNotBlank(bmsDxGroupBuy.getGroupPhotos())){
            List<String> groupPhotos = JSON.parseArray(bmsDxGroupBuy.getGroupPhotos(),String.class);
            if(groupPhotos.size() > 0){
                bmsDxGroupBuy.setGroupImg(groupPhotos.get(0));
                bmsDxGroupBuy.setGroupOriginImg(groupPhotos.get(0));
            }
        }
        //新增所有团购图片小图
        if(StringUtils.isNotBlank(bmsDxGroupBuy.getGroupPhotosSmall())){
            List<String> getGroupPhotosSmall = JSON.parseArray(bmsDxGroupBuy.getGroupPhotosSmall(),String.class);
            if(getGroupPhotosSmall.size() > 0){
                bmsDxGroupBuy.setGroupImg(getGroupPhotosSmall.get(0));
            }
        }
        postHandleDiscount(bmsDxGroupBuy);
        bmsDxGroupBuyDao.save(bmsDxGroupBuy);
        postHandleGroupBuy(bmsDxGroupBuy);
        return ResultMapHelper.success(bmsDxGroupBuy, ResultMsg.INSERT_SUCCESS);
    }

    private void pushGrouPhotos(DxGroupBuyReDto dxGroupBuyReDto) {
        if(StringUtils.checkAnyNotNull(dxGroupBuyReDto.getGroupImg())){
            String url = dxGroupBuyReDto.getGroupImg();
            String url2 = url.substring(0,url.lastIndexOf("."));
            if(!url2.endsWith("_s")){
                url = url.replace(url2,url2.concat("_s"));
            }
            dxGroupBuyReDto.setGroupImg(url);
        }
        if(StringUtils.checkAnyNotNull(dxGroupBuyReDto.getGroupPhotos())){
            List<String> groupPhotos = JSON.parseArray(dxGroupBuyReDto.getGroupPhotos(),String.class);
            List<String> groupPhotosSmall = new ArrayList<>();
            if(groupPhotos.size() > 0){
                for(String p:groupPhotos){
                    String url = p;
                    String url2 = url.substring(0,url.lastIndexOf("."));
                    if(!url2.endsWith("_s")){
                        url = url.replace(url2,url2.concat("_s"));
                    }
                    groupPhotosSmall.add(url);
                }
                dxGroupBuyReDto.setGroupPhotosSmall(JSON.toJSONString(groupPhotosSmall));
            }
        }
    }



    private void postHandleArgInit(DxGroupBuyReDto dxGroupBuyReDto) {
        BeanUtils.setArgs(dxGroupBuyReDto,new String[]{"isRefundAnyTime","isOverdueRefund"},null,Constants.COMMON_FLAG_TRUE_INT);
        BeanUtils.setArgs(dxGroupBuyReDto,new String[]{"isFreePackage",
                "isUseTheRoom","isEnjoyOtherBen"},null,Constants.COMMON_FLAG_FALSE_INT);
    }


    public Map<String, Object> businessFindGroupBuy(DxGroupBuyReDto dxGroupBuyReDto) {
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(Integer.parseInt(dxGroupBuyReDto.getUserId()),dxGroupBuyReDto.getBusinessId());
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Map<Integer,String> sortRuleMap = new HashMap<Integer,String>(){{
            put(Constants.NOT_ONLINE_STATUS,"auditTime");
            put(Constants.ONLINE_STATUS,"onlineTime");
            put(Constants.ROLLED_ONLINE_STATUS,"offlineTime");
            put(Constants.DRAFT_BOX_STATUS,"updateTime");
        }};
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("status",dxGroupBuyReDto.getStatus());
        conditionMap.put("textContent_N",Constants.COMMON_FLAG_FALSE_INT);
        if(dxGroupBuyReDto.getStatus() == Constants.DRAFT_BOX_STATUS){
            Set<Integer> statuses = new HashSet<>();
            statuses.add(dxGroupBuyReDto.getStatus());
            statuses.add(Constants.REFUSED_STATUS);
            conditionMap.put("status_IN",statuses);
            conditionMap.remove("status");
        }
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("businessId",dxGroupBuyReDto.getBusinessId());
        Set<Integer> groupTypes = new HashSet<>();
        groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_GEN);
        groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_TETE);
        //groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_POSTERS);
        conditionMap.put("groupType_IN",groupTypes);
        String orderField = sortRuleMap.get(dxGroupBuyReDto.getStatus());
        Pageable pageable = BmsCommonService.getPageable(dxGroupBuyReDto.getPageNum(),dxGroupBuyReDto.getPageSize(), Sort.Direction.DESC,orderField);
        Page<BmsDxGroupBuy> bmsDxGroupBuyPage = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyPage.getContent();
        postHandleGroupContent(bmsDxGroupBuys,true);
        postHandleBusiness(bmsDxGroupBuys);
        postHandleDraftBoxGroupBuy(bmsDxGroupBuys);
        Map<String,Object> userDataMap = new LinkedHashMap<>();
        userDataMap.put("count",bmsDxGroupBuyPage.getTotalElements());
        return ResultMapHelper.success(bmsDxGroupBuys, ResultMsg.MSG_GET_SUCCESS);
    }

    private void postHandleDraftBoxGroupBuy(BmsDxGroupBuy bmsDxGroupBuy) {
        List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
        bmsDxGroupBuys.add(bmsDxGroupBuy);
        postHandleDraftBoxGroupBuy(bmsDxGroupBuys);
    }

    private void postHandleDraftBoxGroupBuy(List<BmsDxGroupBuy> bmsDxGroupBuys) {
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                if(bmsDxGroupBuy.getStatus() == Constants.REFUSED_STATUS){
                    bmsDxGroupBuy.setStatus(Constants.DRAFT_BOX_STATUS);
                }
            }
        }
    }

    @Override
    public Map<String, Object> businessUpdateGroupBuy(DxGroupBuyReDto dxGroupBuyReDto) {
        //处理图片大小图
        pushGrouPhotos(dxGroupBuyReDto);
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(Integer.parseInt(dxGroupBuyReDto.getUserId()),dxGroupBuyReDto.getBusinessId());
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Integer groupBuyId = dxGroupBuyReDto.getId();
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyDao.findByIdAndIsDelete(groupBuyId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupBuy == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY,ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
        }
        //判断团购券是否是已上线/待上线状态
        if(bmsDxGroupBuy.getStatus() == Constants.ONLINE_STATUS ||
                bmsDxGroupBuy.getStatus() == Constants.NOT_ONLINE_STATUS){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUOP_NO_UPADTE,ResultMsg.CODE_BUSINESS_GROUOP_NO_UPADTE);
        }
        boolean needCreateBuyRecord = false;
        if(bmsDxGroupBuy.getStatus() == Constants.ROLLED_ONLINE_STATUS){
            BmsDxGroupBuy newBmsDxGroupBuy = new BmsDxGroupBuy();
            BeanUtils.copyProperties(bmsDxGroupBuy,newBmsDxGroupBuy);
            dxGroupBuyReDto.setId(null);
            bmsDxGroupBuy = newBmsDxGroupBuy;
            needCreateBuyRecord = true;
        }
        if(dxGroupBuyReDto.getGroupContentArgs() != null){
            dxGroupBuyReDto.setGroupContent(dxGroupBuyReDto.getGroupContentArgs());
        }
        if(dxGroupBuyReDto.getUseTimeArg() != null){
            Integer useWay =  dxGroupBuyReDto.getUseTimeArg().getUseWay();
            if(useWay == Constants.USE_IN_DAY){
                dxGroupBuyReDto.setUseTime(Constants.USE_IN_DAY_DES);
            }else if(useWay == Constants.USE_IN_DAY_PART){
                dxGroupBuyReDto.setUseTime(StringUtils.join(dxGroupBuyReDto.getUseTimeArg().getUseTime(),","));
            }else if(useWay == Constants.USE_IN_DAY_BUS_HOUR){
                dxGroupBuyReDto.setUseTime("营业时间可用");
            }
        }
        if(dxGroupBuyReDto.getExpireTimeArg() != null){
            Integer expireWay = dxGroupBuyReDto.getExpireTimeArg().getExpireWay();
            if(expireWay == Constants.EXPIRE_IN_MONTH){
                dxGroupBuyReDto.setExpireMonth(dxGroupBuyReDto.getExpireTimeArg().getCustomExpireTime());
            }else if(expireWay == Constants.EXPIRE_IN_COS_DATE){
                dxGroupBuyReDto.setExpireTime(DateTimeUtils.converStringToDate(dxGroupBuyReDto.getExpireTimeArg().getCustomExpireTime()));
            }
        }
        if(StringUtils.isNotBlank(dxGroupBuyReDto.getGroupPhotos())){
            List<String> groupPhotos = JSON.parseArray(dxGroupBuyReDto.getGroupPhotos(),String.class);
            if(groupPhotos.size() > 0){
                dxGroupBuyReDto.setGroupImg(groupPhotos.get(0));
                dxGroupBuyReDto.setGroupOriginImg(groupPhotos.get(0));
            }
        }
        if(StringUtils.isNotBlank(dxGroupBuyReDto.getGroupPhotosSmall())){
            List<String> groupPhotosSmall = JSON.parseArray(dxGroupBuyReDto.getGroupPhotosSmall(),String.class);
            if(groupPhotosSmall.size() > 0){
                dxGroupBuyReDto.setGroupImg(groupPhotosSmall.get(0));
            }
        }
        //状态无法修改
        //noUpdate(dxGroupBuyReDto);
        dxGroupBuyReDto.setStatus(bmsDxGroupBuy.getStatus());
        //BeanUtils.copyProperties(dxGroupBuyReDto,bmsDxGroupBuy,BeanUtils.getNullPropertyNames(dxGroupBuyReDto));
        BeanUtils.copyProperties(dxGroupBuyReDto,bmsDxGroupBuy);
        bmsDxGroupBuy.setStatus(Constants.DRAFT_BOX_STATUS);
        postHandleDiscount(bmsDxGroupBuy);
        bmsDxGroupBuyDao.save(bmsDxGroupBuy);
        if(needCreateBuyRecord){
            bmsDxGroupBuyRecordService.addGroupBuyRecord(bmsDxGroupBuy,BmsDxGroupBuyRecordService.RECORD_CRAETE);
        }
        postHandleGroupBuy(bmsDxGroupBuy);
        return ResultMapHelper.success(bmsDxGroupBuy,ResultMsg.UPDATE_SUCCESS);
    }

    private void postHandleGroupBuy(BmsDxGroupBuy bmsDxGroupBuy) {
        List<BmsDxGroupBuy> bmsDxGroupBuys = new LinkedList<>();
        bmsDxGroupBuys.add(bmsDxGroupBuy);
        postHandleGroupContent(bmsDxGroupBuys,false);
        postHandleBusiness(bmsDxGroupBuys);
        postHandleBasicGroupBuy(bmsDxGroupBuy);
        //如果没有开通线上买单，自动开通线上买单
        //postHandleOpenCoupon(bmsDxGroupBuy);
    }

    public void postHandleGroupBuy(BmsDxGroupBuy bmsDxGroupBuy,boolean isDisplay) {
        List<BmsDxGroupBuy> bmsDxGroupBuys = new LinkedList<>();
        bmsDxGroupBuys.add(bmsDxGroupBuy);
        postHandleGroupContent(bmsDxGroupBuys,isDisplay);
        //如果没有开通线上买单，自动开通线上买单
        //postHandleOpenCoupon(bmsDxGroupBuy);
    }

    private void postHandleBasicGroupBuy(BmsDxGroupBuy bmsDxGroupBuy) {

    }

    private void postHandleOpenCoupon(BmsDxGroupBuy bmsDxGroupBuy) {
        List<BmsDxCoupon> bmsDxCoupons = bmsDxCouponService.getBaseDao().findByBmsBusinessIdAndType(bmsDxGroupBuy.getBusinessId(),Constants.COUPON_ONLINE);
        if(!(bmsDxCoupons != null && bmsDxCoupons.size() > 0)){
            BmsDxCoupon bmsDxCoupon = new BmsDxCoupon();
            bmsDxCoupon.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
            bmsDxCoupon.setType(Constants.COUPON_ONLINE);
            bmsDxCoupon.setBmsBusinessId(bmsDxGroupBuy.getBusinessId());
            bmsDxCouponService.getBaseDao().save(bmsDxCoupon);
        }
    }

    private void noUpdate(DxGroupBuyReDto dxGroupBuyReDto){
        dxGroupBuyReDto.setStatus(null);
    }

    @Override
    @Transactional
    public Map<String, Object> businessUpdateGroupBuyStatus(DxGroupBuyReDto dxGroupBuyReDto) {
        //判断团购券存在
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyDao.findByIdAndIsDelete(dxGroupBuyReDto.getId(),Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupBuy == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY,ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
        }
        //判断是否用户商家
        Integer userId = Integer.parseInt(dxGroupBuyReDto.getUserId());
        Integer businessId = dxGroupBuyReDto.getBusinessId();
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        //判断团购券是否属于商家
        if(bmsDxGroupBuy.getBusinessId() != businessId.intValue()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG,ResultMsg.CODE_BUSINESS_NO_BELONG);
        }
        Integer action = dxGroupBuyReDto.getAction();
        Date nowTime = new Date();
        boolean needCreateBuyRecord = false;
        BmsDxGroupBuy resultGroupBuy = null;
        if(action == Constants.AC_OFFLINE) {
            if(bmsDxGroupBuy.getStatus() == Constants.OFFLINE_STATUS){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUOP_AL_OFFLINE,ResultMsg.CODE_BUSINESS_GROUOP_AL_OFFLINE);
            }
            bmsDxGroupBuy.setStatus(Constants.ROLLED_ONLINE_STATUS);
            bmsDxGroupBuy.setOfflineTime(nowTime);
            bmsDxGroupBuyRecordService.addGroupBuyRecord(bmsDxGroupBuy,BmsDxGroupBuyRecordService.RECORD_OFFLINE);
            //同时新建一个全新的到已下线的团购券
            /*BmsDxGroupBuy newBmsGroupBuy = new BmsDxGroupBuy();
            BeanUtils.copyProperties(bmsDxGroupBuy,newBmsGroupBuy);
            newBmsGroupBuy.setStatus(Constants.ROLLED_ONLINE_STATUS);
            newBmsGroupBuy.setId(null);
            newBmsGroupBuy.setSellNum(Constants.COMMON_FLAG_FALSE_INT);
            newBmsGroupBuy.setFinishNum(Constants.COMMON_FLAG_FALSE_INT);
            newBmsGroupBuy.setViewsNum(Constants.COMMON_FLAG_FALSE_INT);
            bmsDxGroupBuyDao.save(newBmsGroupBuy);*/
        }else if(action == Constants.AC_ONLINE){
            if(bmsDxGroupBuy.getStatus() == Constants.NOT_ONLINE_STATUS){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUOP_AL_COMMIT,ResultMsg.CODE_BUSINESS_GROUOP_AL_COMMIT);
            }
            if(bmsDxGroupBuy.getStatus() == Constants.ROLLED_ONLINE_STATUS){
                BmsDxGroupBuy newBmsDxGroupBuy = new BmsDxGroupBuy();
                bmsDxGroupBuy.setFinishNum(Constants.COMMON_FLAG_FALSE_INT);
                bmsDxGroupBuy.setSellNum(Constants.COMMON_FLAG_FALSE_INT);
                bmsDxGroupBuy.setBargainNum(Constants.COMMON_FLAG_FALSE_INT);
                bmsDxGroupBuy.setRefundNum(Constants.COMMON_FLAG_FALSE_INT);
                BeanUtils.copyProperties(bmsDxGroupBuy,newBmsDxGroupBuy);
                newBmsDxGroupBuy.setId(null);
                bmsDxGroupBuy = newBmsDxGroupBuy;
                needCreateBuyRecord = true;
            }
            bmsDxGroupBuy.setStatus(Constants.NOT_ONLINE_STATUS);
            bmsDxGroupBuy.setAuditTime(nowTime);
            bmsDxGroupBuy.setSellInventory(bmsDxGroupBuy.getLimitSellNum());
            if(StringUtils.isNotBlank(bmsDxGroupBuy.getExpireMonth())){
                bmsDxGroupBuy.setExpireTime(DateTimeUtils.addMonth(nowTime,Integer.parseInt(bmsDxGroupBuy.getExpireMonth())));
            }
        }else if(action == Constants.AC_CANCEL_AUDIT){
            if(bmsDxGroupBuy.getStatus() == Constants.DRAFT_BOX_STATUS){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUOP_AL_CAN_COM,ResultMsg.CODE_BUSINESS_GROUOP_AL_CAN_COM);
            }
            bmsDxGroupBuy.setStatus(Constants.DRAFT_BOX_STATUS);
            bmsDxGroupBuy.setUpdateTime(nowTime);
        }
        bmsDxGroupBuyDao.save(bmsDxGroupBuy);
        if(needCreateBuyRecord){
            bmsDxGroupBuyRecordService.addGroupBuyRecord(bmsDxGroupBuy,BmsDxGroupBuyRecordService.RECORD_CRAETE);
        }
        return ResultMapHelper.success(bmsDxGroupBuy,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> businessDeleteGroupBuy(DxGroupBuyReDto dxGroupBuyReDto) {
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyDao.findByIdAndIsDelete(dxGroupBuyReDto.getId(),Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupBuy == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY,ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
        }
        if(bmsDxGroupBuy.getBusinessId() != dxGroupBuyReDto.getBusinessId().intValue()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG,ResultMsg.CODE_BUSINESS_NO_BELONG);
        }
        bmsDxGroupBuy.setIsDelete(Constants.COMMON_FLAG_TRUE_INT);
        bmsDxGroupBuyDao.save(bmsDxGroupBuy);
        return ResultMapHelper.success(null,ResultMsg.DELETE_SUCCESS);
    }

    @Override
    public Map<String, Object> userGetBusinessGroupBuy(ParamsMap paramsMap) throws Exception {
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        int client = requestHeaderData.getInteger("client");
        Map<String,Object> conditionMap = new HashMap<>();
        boolean isFindId = false;
        if(StringUtils.checkNullAndEmpty(paramsMap.getString("groupCode")) ||
                StringUtils.checkNullAndEmpty(paramsMap.getString("id"))){
            Integer groupBuyId;
            if(StringUtils.checkNullAndEmpty(paramsMap.getString("groupCode"))){
                groupBuyId = Integer.parseInt(DESUtil.decrypt(paramsMap.getString("groupCode")));
            }else {
                groupBuyId = Integer.parseInt(paramsMap.getString("id"));
            }
            conditionMap.put("id",groupBuyId);
            isFindId = true;
        }else {
            Integer businessId = paramsMap.getInteger("businessId");
            if(!StringUtils.checkNullAndEmpty(businessId)){
                return ResultMapHelper.result(ResultCode.CODE_ERROR_03,"缺少businessId");
            }
            conditionMap.put("businessId",businessId);
            conditionMap.put("status",Constants.ONLINE_STATUS);
        }
        Integer pageNum = paramsMap.getInteger("pageNum");
        Integer pageSize = paramsMap.getInteger("pageSize");
        if(!StringUtils.checkNullAndEmpty(pageNum)){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_03,"缺少pageNum");
        }
        if(!StringUtils.checkNullAndEmpty(pageSize)){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_03,"缺少pageSize");
        }
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"onlineTime");
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        Set<Integer> groupTypes = new HashSet<>();
        groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_GEN);
        groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_TETE);
        groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_SECONDS_KILL);
        //groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_POSTERS);
        if(client == Constants.SMALL_PROGRAM){
            groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_BARGAIN);
        }
        conditionMap.put("groupType_IN",groupTypes);
        Page<BmsDxGroupBuy> bmsDxGroupBuyPage = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyPage.getContent();
        postHandleBusiness(bmsDxGroupBuys);
        postHandleGroupContent(bmsDxGroupBuys,true);
        //清空缓存
        for(BmsDxGroupBuy v:bmsDxGroupBuys){
            if(entityManager.contains(v)) {
                entityManager.unwrap(Session.class).evict(v);
            }
        }
        postHandleGroupGif(bmsDxGroupBuys);
        for(BmsDxGroupBuy v:bmsDxGroupBuys){
            if(!StringUtils.checkAnyNotNull(v.getGroupPhotosSmall())){
                v.setGroupPhotosSmall(v.getGroupPhotos());
            }
            List<Map<String,Object>> groupList = new ArrayList<>();
            List<Map<String,Object>> groupSmallList = new ArrayList<>();
            if(v.getStatus() == Constants.COMMON_FLAG_TRUE_INT && v.getIsTimeLimit() == Constants.COMMON_FLAG_TRUE_INT){
                bmsDxConfigService.pushResultTime(v);
            }
            if(StringUtils.checkAnyNotNull(v.getCloudFileUrl())){
                Map map = new HashMap();
                map.put("url",v.getCloudFileUrl());
                map.put("type",1);
                groupList.add(map);
                groupSmallList.add(map);
            }
            if(StringUtils.checkAnyNotNull(v.getGroupPhotos())) {
                JSONArray jsonArray = JSON.parseArray(v.getGroupPhotos());
                jsonArray.forEach(pic -> {
                    Map map = new HashMap();
                    map.put("url", pic);
                    map.put("type", 0);
                    groupList.add(map);
                });
            }
            if(StringUtils.checkAnyNotNull(v.getGroupPhotosSmall())) {
                JSONArray jsonArray = JSON.parseArray(v.getGroupPhotosSmall());
                jsonArray.forEach(pic -> {
                    Map map = new HashMap();
                    map.put("url", pic);
                    map.put("type", 0);
                    groupSmallList.add(map);
                });
            }

            v.setGroupPhotos2(JSON.toJSONString(groupList));
            v.setGroupPhotosSmall2(JSON.toJSONString(groupSmallList));
        }
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("serverTime",new Date());
        userDataMap.put("count",bmsDxGroupBuyPage.getTotalElements());

        //处理图片字段
        bmsDxGroupBuys.forEach(v->{
            //如果团购小图为空则默认为groupPhotos
            if(!StringUtils.checkAnyNotNull(v.getGroupPhotosSmall())){
                v.setGroupPhotosSmall(v.getGroupPhotos());
            }
            imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
            if(v.getBmsBusiness() != null){
                imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

            }});
        imgPrefixService.pushSpliceField(bmsDxGroupBuys,"groupImg","cloudCoverUrl","groupPhotos","groupPhotosSmall","groupPhotos2","groupPhotosSmall2");

        if(isFindId){
            if(bmsDxGroupBuys.size() > 0) {
                BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuys.get(0);
                CheckUserBo checkUserBo = RequestParamUtils.checkUserBo();
                if (checkUserBo.getCheckStatus().equals(ResultCode.CODE_NORMAL)) {
                    Integer userIdentify = Integer.parseInt(checkUserBo.getUserId());
                    BmsCommonService.getApplicationContext().publishEvent(new GetGroupBuyDetailEvent("groupBuyDetail", bmsDxGroupBuy, userIdentify));
                }
            }
            return ResultMapHelper.success(bmsDxGroupBuys,userDataMap,ResultMsg.MSG_GET_SUCCESS);
        }
        List<GetAllGroupBuy_v2Vo> getAllGroupBuy_v2Vos = postHandleCleanData(bmsDxGroupBuys);
        return ResultMapHelper.success(getAllGroupBuy_v2Vos,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public void postHandleGroupGif(List<BmsDxGroupBuy> bmsDxGroupBuyList){
        //更新返回
        for(BmsDxGroupBuy item:bmsDxGroupBuyList){
            if(item.getHasGif()==Constants.COMMON_FLAG_TRUE_INT){
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(item.getGroupGif());
                if(StringUtils.checkAnyNotNull(item.getGroupPhotos())){
                    JSONArray arr = JSON.parseArray(item.getGroupPhotos());
                    jsonArray.addAll(arr);
                }
                item.setGroupPhotos(jsonArray.toJSONString());

            }
        }
    }

    public void postHandleBusiness(BmsDxGroupBuy bmsDxGroupBuy){
        if(bmsDxGroupBuy != null ){
            List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
            bmsDxGroupBuys.add(bmsDxGroupBuy);
            postHandleBusiness(bmsDxGroupBuys);
        }
    }

    public void postHandleBusiness(List<BmsDxGroupBuy> bmsDxGroupBuyList){
        if(bmsDxGroupBuyList != null && bmsDxGroupBuyList.size() > 0){
            Set businessIds = new HashSet();
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuyList){
                businessIds.add(bmsDxGroupBuy.getBusinessId());
            }
            if(businessIds.size() > 0){
                Map<Integer, BmsBusiness> bmsBusinessMap = bmsBusinessService.findBusinessByIds(businessIds);
                for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuyList){
                    if(bmsBusinessMap.containsKey(bmsDxGroupBuy.getBusinessId())){
                        BusinessRpDto businessRpDto = new BusinessRpDto();
                        BeanUtils.copyProperties(bmsBusinessMap.get(bmsDxGroupBuy.getBusinessId()),businessRpDto);
                        bmsDxGroupBuy.setBmsBusiness(businessRpDto);
                    }
                }
            }
        }
    }

    public void postHandleBusinessIgnoreBuyCoupon(List<BmsDxGroupBuy> bmsDxGroupBuyList){
        if(bmsDxGroupBuyList != null && bmsDxGroupBuyList.size() > 0){
            Set businessIds = new HashSet();
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuyList){
                businessIds.add(bmsDxGroupBuy.getBusinessId());
            }
            if(businessIds.size() > 0){
                Map<Integer, BmsBusiness> bmsBusinessMap = bmsBusinessService.findBusinessByIdsIgnoreSetBuyCoupon(businessIds);
                for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuyList){
                    if(bmsBusinessMap.containsKey(bmsDxGroupBuy.getBusinessId())){
                        BusinessRpDto businessRpDto = new BusinessRpDto();
                        BeanUtils.copyProperties(bmsBusinessMap.get(bmsDxGroupBuy.getBusinessId()),businessRpDto);
                        bmsDxGroupBuy.setBmsBusiness(businessRpDto);
                    }
                }
            }
        }
    }

    public void postHandleGroupContent(BmsDxGroupBuy bmsDxGroupBuy){
        List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
        bmsDxGroupBuys.add(bmsDxGroupBuy);
        postHandleGroupContent(bmsDxGroupBuys,true);
    }

    /**
     * @Description 处理团购内容
     * @Author: cfx
     * @param: 团购列表
     * @param: 是否显示删除内容
     * @Date: 2019/7/26
     */
    public void postHandleGroupContent(List<BmsDxGroupBuy> bmsDxGroupBuyList,boolean isDisplayDelete){
        if(bmsDxGroupBuyList != null && bmsDxGroupBuyList.size() > 0){
            Set<Integer> libraryIds = new HashSet<>();
            Set<Integer> subIds = new HashSet<>();
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuyList){
                String groupContent = bmsDxGroupBuy.getGroupContent();
                if(StringUtils.isNotBlank(groupContent)) {
                    JSONArray contents = JSON.parseArray(groupContent);
                    for (int ii = 0; ii < contents.size(); ii++) {
                        JSONObject jsonObject = contents.getJSONObject(ii);
                        Integer libraryId = jsonObject.getInteger("libraryId");
                        libraryIds.add(libraryId);
                        List<GrSubFood> subIdsTmp = JSONObject.parseArray(jsonObject.get("subData").toString(), GrSubFood.class);
                        for (GrSubFood grSubFood : subIdsTmp) {
                            subIds.add(grSubFood.getSubId());
                        }
                    }
                }
            }
            //查询菜品库类型数据
            Map<Integer,BmsDxFoodLibrary> bmsDxFoodLibraryMap = bmsDxFoodLibraryService.getFoodLibraryByIds(libraryIds,isDisplayDelete);
            Map<Integer, BmsDxSubFood> bmsDxSubFoodMap = bmsDxSubFoodService.getSubFoodByIds(subIds,isDisplayDelete);
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuyList) {
                String groupContent = bmsDxGroupBuy.getGroupContent();
                if (StringUtils.isNotBlank(groupContent)) {
                    JSONArray contents = JSON.parseArray(groupContent);
                    List<GroupContentRpDto> groupContents = new LinkedList<>();
                    bmsDxGroupBuy.setGroupContentRpDto(groupContents);
                    for (int ii = 0; ii < contents.size(); ii++) {
                        JSONObject jsonObject = contents.getJSONObject(ii);
                        Integer libraryId = jsonObject.getInteger("libraryId");
                        if (bmsDxFoodLibraryMap.containsKey(libraryId)) {
                            GroupContentRpDto groupContentRpDto = new GroupContentRpDto();
                            groupContentRpDto.setLibraryId(libraryId);
                            groupContentRpDto.setFoodTypeName(bmsDxFoodLibraryMap.get(libraryId).getFoodTypeName());
                            String choose = jsonObject.getString("choose");
                            groupContentRpDto.setChoose(choose);
                            groupContents.add(groupContentRpDto);
                            List<BmsDxSubFood> bmsDxSubFoods = new LinkedList<>();
                            groupContentRpDto.setBmsDxSubFoods(bmsDxSubFoods);
                            List<GrSubFood> subIdsTmp = JSONObject.parseArray(jsonObject.get("subData").toString(), GrSubFood.class);
                            for (GrSubFood grSubFood : subIdsTmp) {
                                if (bmsDxSubFoodMap.containsKey(grSubFood.getSubId())) {
                                    BmsDxSubFood bmsDxSubFood = bmsDxSubFoodMap.get(grSubFood.getSubId());
                                    BmsDxSubFood newBmsDxSubFood = new BmsDxSubFood();
                                    BeanUtils.copyProperties(bmsDxSubFood, newBmsDxSubFood);
                                    newBmsDxSubFood.setFoodNum(grSubFood.getNum());
                                    bmsDxSubFoods.add(newBmsDxSubFood);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public BmsDxGroupBuy getGroupBuyById(Integer groupBuyId) {
        return bmsDxGroupBuyDao.findByIdAndIsDelete(groupBuyId,Constants.COMMON_FLAG_FALSE_INT);
    }

    public Map<Integer,BmsDxGroupBuy> getGroupBuyById(Set groupBuyIds){
        Map<Integer,BmsDxGroupBuy> bmsDxGroupBuyMap = new HashMap<>();
        if(groupBuyIds.size() > 0) {
            List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findByIdIn(groupBuyIds);
            postHandleGroupContent(bmsDxGroupBuys,false);
            postHandleBusiness(bmsDxGroupBuys);
            if (bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0) {
                for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                    bmsDxGroupBuyMap.put(bmsDxGroupBuy.getId(),bmsDxGroupBuy);
                }
            }
        }
        return bmsDxGroupBuyMap;
    }

    @Override
    public boolean checkIsOpenGroupBuy(Integer businessId) {
        if(!bmsBusinessinfoService.checkBusinessHavingPayInfo(businessId)){
           return false;
        }
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("businessId",businessId);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("status",Constants.ONLINE_STATUS);
        Long num = bmsDxGroupBuyDao.count(new SpecificationUtils(conditionMap));
        if(num > 0){
            return true;
        }
        return false;
    }

    @Override
    public Map<Integer, Integer> checkIsOpenGroupBuy(Set<Integer> businessIds) {
        Map<Integer,Integer> isOpenGroupBuyMap = new HashMap<>();
        if(businessIds.size() > 0){
            Map<Integer,BmsDxGroupBuy> bmsDxGroupBuyMap = getBusinessOnceGroupBuyMap(businessIds);
            Map<Integer, BmsBusinessInfo> bmsBusinessInfoMap = bmsBusinessinfoService.getBmsBusinessInfoMap(businessIds);
            for(Integer buinessId : businessIds){
                if(bmsDxGroupBuyMap.containsKey(buinessId) && bmsBusinessInfoMap.containsKey(buinessId)){
                    isOpenGroupBuyMap.put(buinessId,Constants.COMMON_FLAG_TRUE_INT);
                }
            }
        }
        return isOpenGroupBuyMap;
    }

    public Map<Integer,BmsDxGroupBuy> getBusinessOnceGroupBuyMap(Set businessIds){
        Map<Integer,BmsDxGroupBuy> groupBuyMap = new HashMap<>();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("businessId_IN",businessIds);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("status",Constants.ONLINE_STATUS);
        Map<String,Object> groupByMap = new HashMap<>();
        groupByMap.put("businessId_GB",Constants.COMMON_FLAG_FALSE_INT);
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap,groupByMap));
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                groupBuyMap.put(bmsDxGroupBuy.getBusinessId(),bmsDxGroupBuy);
            }
        }
        return groupBuyMap;
    }

    @Override
    public Map<String, Object> businessUserVerGroupBuy(GroupBuyUseReDto groupBuyUseReDto) {
        //购买券
        final int BUY_COUPON = 1;
        //派发券
        final int PA_COUPON = 2;
        Integer verWay = BUY_COUPON;
        if(groupBuyUseReDto.getVerWay() != null){
            verWay = groupBuyUseReDto.getVerWay();
        }
        if(StringUtils.isNotBlank(groupBuyUseReDto.getVerId())){
            String verId = groupBuyUseReDto.getVerId();
            BmsVerRecord bmsVerRecord = bmsVerRecordService.getRecodeByVerId(verId);
            if(bmsVerRecord != null){
                if(bmsVerRecord.getVerType() == BUY_COUPON){
                    groupBuyUseReDto.setOrderId(bmsVerRecord.getOrderId());
                }else if(bmsVerRecord.getVerType() == PA_COUPON){
                    groupBuyUseReDto.setUserCouponId(bmsVerRecord.getReceId());
                }
                groupBuyUseReDto.setVerWay(bmsVerRecord.getVerType());
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        if(verWay == BUY_COUPON) {
            ReGroupUseLog reGroupUseLog = new ReGroupUseLog();
            ReTransferLog reTransferLog = new ReTransferLog();
            Integer orderId = groupBuyUseReDto.getOrderId();
            String verOrderKey = Constants.REDIS_KEY_ORDER_VER + orderId;
            //Long threadId = Thread.currentThread().getId();
            if(!RedisTemplateUtils.addLock(verOrderKey,1000)){
                return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.REPEAT_MSG);
            }
            try {
                //System.out.println("订单：" + orderId + "获取了锁！！！！！！！！！！！！！！！！！！！！！！！" + "线程id：" + threadId);
                resultMap = bmsDxGroupBuyService.businessUserVerGroupBuy(reGroupUseLog, reTransferLog, groupBuyUseReDto);
            } catch (Exception e) {
                log.error("核销错误：",e);
                reGroupUseLog.setError(e.toString());
                resultMap = ResultMapHelper.failure(ResultMsg.HAND_FAIL);
            } finally {
                reGroupUseLogService.getBaseDao().save(reGroupUseLog);
                if (reTransferLog.getNewTime() != null) {
                    reTransferLogService.getBaseDao().save(reTransferLog);
                }
                RedisTemplateUtils.releaseLock(verOrderKey);
                //System.out.println("订单：" + orderId + "释放了锁！！！！！！！！！！！！！！！！！！！！！！！" + "线程id：" + threadId);
            }
        }else if(verWay == PA_COUPON){
            resultMap = bmsUserReceCouponService.verBusinessCoupon(Integer.parseInt(groupBuyUseReDto.getUserId()),groupBuyUseReDto.getUserCouponId(),groupBuyUseReDto.getBusinessId());
        }
        return resultMap;
    }

    @GlobalTransactional(rollbackFor = Exception.class)
    public Map<String, Object> businessUserVerGroupBuy(ReGroupUseLog reGroupUseLog,ReTransferLog reTransferLog,GroupBuyUseReDto groupBuyUseReDto) throws Exception {
        final int verStatusInSweep = 1;
        final int verStatusInCode = 2;
        Date nowTime = new Date();
        BmsDxOrder bmsDxOrder = bmsDxOrderService.getBaseDao().findByIdAndIsDelete(groupBuyUseReDto.getOrderId(),Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxOrder == null){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST,ResultMsg.CODE_ORDER_NO_EXIST);
        }
        Integer userId = Integer.parseInt(groupBuyUseReDto.getUserId());
        Set<Integer> buinessIds = bmsUserBusinessService.findUserHavingBusiness(userId);
        if(!(buinessIds != null && buinessIds.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_110,ResultMsg.CODE_ERROR_110);
        }
        //开始核销
        //判断核销的数量是否超过团购券的单次使用量
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
        Integer busId = null;
        boolean isCheck = true;
        for(Integer businessId : buinessIds) {
            if (businessId.intValue() == bmsDxGroupBuy.getBusinessId().intValue()) {
                isCheck = false;
                busId = businessId;
            }
        }
        if(isCheck){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG, ResultMsg.CODE_BUSINESS_NO_BELONG);
        }
        //再判断一下当前店铺是否是核销的店
        if(groupBuyUseReDto.getBusinessId() != null) {
            if (busId.intValue() != groupBuyUseReDto.getBusinessId().intValue()) {
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG, ResultMsg.CODE_BUSINESS_NO_BELONG);
            }
        }
        if(bmsDxGroupBuy.getExpireTime() != null){
            Date overTime = DateTimeUtils.addDay(bmsDxGroupBuy.getExpireTime(),1);
            if(nowTime.getTime() >= overTime.getTime()){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_EXPIRE,ResultMsg.CODE_BUSINESS_GROUP_EXPIRE);
            }
        }
        if(bmsDxGroupBuy.getIsTimeLimit() != null && bmsDxGroupBuy.getIsTimeLimit() == Constants.COMMON_FLAG_TRUE_INT){
            Date startTime = bmsDxGroupBuy.getUseStartTime();
            Date endTime = bmsDxGroupBuy.getUseEndTime();
            if(startTime != null && DateTimeUtils.match(nowTime,startTime,DateTimeUtils.MATCH_MODEL_LT)){
                return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_NOT_TIME_FOR_USE);
            }
            if(endTime != null && DateTimeUtils.match(nowTime,endTime,DateTimeUtils.MATCH_MODEL_GT)){
                return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.CODE_BUSINESS_GROUP_EXPIRE);
            }
        }
        Integer buinessId = bmsDxGroupBuy.getBusinessId();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("orderId",groupBuyUseReDto.getOrderId());
        conditionMap.put("status",Constants.GROUP_NO_USE);
        Integer noUseNum = (int)bmsDxGroupBuyUseService.getBaseDao().count(new SpecificationUtils(conditionMap));
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = new LinkedList<>();
        if(groupBuyUseReDto.getVerStatus() == verStatusInSweep){
            //扫码核销
            if(bmsDxGroupBuy.getLimitOnceUse() != null && bmsDxGroupBuy.getLimitOnceUse() > 0) {
                if (groupBuyUseReDto.getVerNum() > bmsDxGroupBuy.getLimitOnceUse()) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_PASS_USE_LIMIT, ResultMsg.CODE_ORDER_GROUP_PASS_USE_LIMIT);
                }
            }
            if(noUseNum < groupBuyUseReDto.getVerNum()){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_OVER,ResultMsg.CODE_ORDER_GROUP_USE_OVER);
            }
            Pageable pageable = BmsCommonService.getPageable(0,groupBuyUseReDto.getVerNum(), Sort.Direction.ASC,"isRefund");
            bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findAll(new SpecificationUtils(conditionMap),pageable).getContent();
        }else if(groupBuyUseReDto.getVerStatus() == verStatusInCode){
            List<String> codes = groupBuyUseReDto.getGroupBuyUseCode();
            //验证码核销
            if(bmsDxGroupBuy.getLimitOnceUse() != null && bmsDxGroupBuy.getLimitOnceUse() > 0) {
                if (codes.size() > bmsDxGroupBuy.getLimitOnceUse() && bmsDxGroupBuy.getLimitOnceUse() > 0) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_PASS_USE_LIMIT, ResultMsg.CODE_ORDER_GROUP_PASS_USE_LIMIT);
                }
            }
            groupBuyUseReDto.setVerNum(codes.size());
            Map<String,Object> codeConditionMap = new HashMap<>();
            codeConditionMap.put("orderId",groupBuyUseReDto.getOrderId());
            codeConditionMap.put("groupBuyCode_IN",new HashSet<>(codes));
            bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findAll(new SpecificationUtils(codeConditionMap));
            if(bmsDxGroupBuyUses.size() != codes.size()){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_ORDER,ResultMsg.CODE_ORDER_GROUP_USE_NO_ORDER);
            }
            if(groupBuyUseReDto.getVerCodeExtraWay() != null && groupBuyUseReDto.getVerCodeExtraWay() == BmsDxGroupBuyService.verStatusInSweep){
                groupBuyUseReDto.setVerStatus(BmsDxGroupBuyService.verStatusInSweep);
            }
        }
        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
            if(bmsDxGroupBuyUse.getStatus() == Constants.GROUP_ALREADY_USE){
                return ResultMapHelper.result(CouponEnums.COUPON_EXIST_USE);
            }else if(bmsDxGroupBuyUse.getStatus() == Constants.GROUP_REFUND_COMPLETE){
                return ResultMapHelper.result(CouponEnums.COUPON_EXIST_HAVE_REFUND);
            }else if(bmsDxGroupBuyUse.getIsRefund() == Constants.COMMON_FLAG_TRUE_INT){
                //查询是否已经退款了
                if(this.searchIsRefundSuccess(bmsDxGroupBuyUse.getGroupBuyCode())){
                    return ResultMapHelper.result(CouponEnums.COUPON_EXIST_HAVE_REFUND);
                }
            }
        }
        //查询用户角色
        Set<Integer> roleIds = new HashSet<>(Arrays.asList(new Integer[]{Constants.BUSINESS_ROLE_ID,Constants.ASSISTANT_ROLE_ID}));
        BmsDxClientRole bmsDxClientRole = bmsDxClientRoleService.getUserClienRole(Integer.parseInt(groupBuyUseReDto.getUserId()),roleIds).get(0);

        //处理核销业务
        Double total = 0d;
        Double shopConsum = 0d;
        Integer orderId = bmsDxOrder.getId();
        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
            bmsDxGroupBuyUse.setStatus(Constants.GROUP_ALREADY_USE);
            bmsDxGroupBuyUse.setUseTime(nowTime);
            bmsDxGroupBuyUse.setUseWay(groupBuyUseReDto.getVerStatus());
            bmsDxGroupBuyUse.setUseManId(Integer.parseInt(groupBuyUseReDto.getUserId()));
            if(bmsDxClientRole != null) {
                bmsDxGroupBuyUse.setUseManRole(bmsDxClientRole.getRoleId());
                if (bmsDxClientRole.getRoleId() == Constants.BUSINESS_ROLE_ID) {
                    bmsDxGroupBuyUse.setNickName(Constants.BUSINESS_NAME);
                }else if(bmsDxClientRole.getRoleId() == Constants.ASSISTANT_ROLE_ID){
                    List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessService.getBaseDao().findByBmsUserIdAndBmsBusinessId(userId,buinessId);
                    if(bmsUserBusinesses != null && bmsUserBusinesses.size() > 0) {
                        bmsDxGroupBuyUse.setNickName(String.format("店员-%s",bmsUserBusinesses.get(0).getNameInStore()));
                    }
                }
            }
            total = ArithUtil.add(total,bmsDxGroupBuyUse.getSettleMoney());
            shopConsum = ArithUtil.add(shopConsum,bmsDxGroupBuyUse.getOnceShopMoney());
        }
        bmsDxGroupBuyUseService.getBaseDao().saveAll(bmsDxGroupBuyUses);
        if(noUseNum == groupBuyUseReDto.getVerNum()){
            //代表刚好消费完了，需改变订单状态
            //BmsDxOrderStatus bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().findByOrderIdAndStatus(groupBuyUseReDto.getOrderId(),Constants.ALREADY_USE);
            //bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
            //bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
            bmsDxOrderStatusService.addOrderStatus(bmsDxOrder,Constants.PAY_COMPLETE);
            bmsDxOrderStatusService.deleteAllRefundStatus(orderId,Constants.ALREADY_USE);
            int refundIngNum = bmsDxGroupBuyUseService.countRefundIngNum(bmsDxOrder.getId());
            if(refundIngNum > 0){
                bmsDxOrderStatusService.deleteAllRefundStatus(orderId,Constants.REFUND_COMPLETE);
                bmsDxOrderStatusService.addOrderStatus(bmsDxOrder,Constants.REFUND_ING);
            }else {
                //查看是否有退款完成记录
                int refundNum = bmsDxGroupBuyUseService.countRefundNum(orderId);
                if (refundNum > 0) {
                    bmsDxOrderStatusService.deleteAllRefundStatus(orderId,Constants.REFUND_ING);
                    bmsDxOrderStatusService.addOrderStatus(bmsDxOrder, Constants.REFUND_COMPLETE);
                }
            }
        }
        //记录核销信息
        recordVerData(reGroupUseLog,bmsDxOrder,total,bmsDxGroupBuyUses);

        //TODO 分销系统核销券码
        if(bmsDxOrder.getOrderType() == Constants.FX_ORDER_TYPE){
            VerifyCodeDto verifyCodeDto = new VerifyCodeDto();
            verifyCodeDto.setUserId(bmsDxOrder.getBmsUserId());
            verifyCodeDto.setOrderId(bmsDxOrder.getId());
            Double shareComm = groupBuyUseReDto.getVerNum() * bmsDxGroupBuy.getAcrossCommision();
            Double buyComm = groupBuyUseReDto.getVerNum() * bmsDxGroupBuy.getCommision();
            verifyCodeDto.setShareComm(BigDecimal.valueOf(shareComm));
            verifyCodeDto.setBuyComm(BigDecimal.valueOf(buyComm));
            if(bmsDxGroupBuy.getIsBusinessConsume() == Constants.COMMON_FLAG_TRUE_INT){
                Map<String, Object> verifyMap = fxCenterService.verifyCode(verifyCodeDto);
            }
        }

        //处理分账业务
        boolean isNeedReadTimeAccount = true;
        //判断是否需要实时分帐
        if(bmsDxGroupBuy.getIsRealTimeAccount() != null
                && bmsDxGroupBuy.getIsRealTimeAccount() == Constants.COMMON_FLAG_FALSE_INT){
            isNeedReadTimeAccount = false;
        }
        if(isNeedReadTimeAccount) {
            List<BmsBusinessInfo> bmsBusinessInfos = bmsBusinessinfoService.getBaseDao().findByBusinessIdAndAlipayStatus(bmsDxOrder.getBmsBusinessId(), Constants.COMMON_FLAG_TRUE_INT);
            if (bmsBusinessInfos != null && bmsBusinessInfos.size() > 0) {
                log.info("开始处理转账任务：" + JSON.toJSONString(bmsBusinessInfos));
                BmsBusinessInfo bmsBusinessInfo = bmsBusinessInfos.get(0);
                Double settleTotal = total;
//                if (settleTotal > 0d) {
//                    //需要分账
//                    Map<String, Object> resultMap = aliPayController.settleForService(bmsDxOrder.getPayNo(), bmsBusinessInfo.getAlipayUid(), settleTotal.toString());
//                    reGroupUseLog.setSettleData(resultMap.get("settleData").toString());
//                    if (resultMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(resultMap.get("status").toString())) {
//                        log.info("分账成功.....................");
//                        reGroupUseLog.setIsSettleSuccess(Constants.COMMON_FLAG_TRUE_INT);
//                    } else {
//                        if (resultMap.containsKey("settleData") && StringUtils.checkNullAndEmpty(resultMap.get("settleData"))) {
//                            reGroupUseLog.setSettleData(resultMap.get("settleData").toString());
//                        }
//                        if (resultMap.containsKey("settleError") && StringUtils.checkNullAndEmpty(resultMap.get("settleError"))) {
//                            reGroupUseLog.setSettleData(resultMap.get("settleError").toString());
//                        }
//                        if (BmsCommonService.checkRunProfile(BmsCommonService.RUN_PRO)) {
//                            throw new Exception("分账错误...........");
//                        }
//                    }
//                }
                //需要转账
                Double transfer;
                if (total > 0d) {
                    transfer = ArithUtil.sub(shopConsum, total);
                } else {
                    transfer = shopConsum;
                }
                if (bmsDxOrder.getPayNo() != null) {
                    if (bmsDxOrder.getPayNo().startsWith("test")) {
                        transfer = 0d;
                    }
                }
                if (transfer > 0d) {
                    Map<String, Object> transMap = aliPayController.transferFullCoupon(bmsDxOrder, bmsBusinessInfo.getAlipayUid(),
                            transfer.toString(), reTransferLog);
                    reGroupUseLog.setTranferLog(JSON.toJSONString(transMap));
                    if (!(transMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(transMap.get("status").toString()))) {
                        if (BmsCommonService.checkRunProfile(BmsCommonService.RUN_PRO)) {
                            throw new Exception("转账错误");
                        }
                    }
                }
                //}
            } else {
                if (BmsCommonService.checkRunProfile(BmsCommonService.RUN_PRO)) {
                    throw new Exception("缺少分账信息...........");
                }
            }
        }
        //添加一个监听事件
        addGroupBuyUseEvent(bmsDxOrder,bmsDxGroupBuyUses);
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    private boolean searchIsRefundSuccess(String groupBuyCode) {
        String codeKey = Constants.REDIS_GROUB_USER_REFUND_ID + groupBuyCode;
        if(RedisTemplateUtils.hasKey(codeKey)){
            String refundId = RedisTemplateUtils.getRedisTemplate().opsForValue().get(codeKey).toString();
            if(StringUtils.isNotBlank(refundId)){
                return wxPayService.refundQueryNoWait(refundId, WxPayBeanFactory.MIN_APP_CHANNEL);
            }
        }
        return false;
    }

    @Override
    public Map<String, Object> businessUserVerGroupBuyByScan(GroupBuyUseReDto groupBuyUseReDto) {
        return null;
    }

    @Override
    public Map<String, Object> businessUserVerGroupBuyByCode(GroupBuyUseReDto groupBuyUseReDto) {
        groupBuyUseReDto.setVerStatus(BmsDxGroupBuyService.verStatusInCode);
        Date nowTime = new Date();
        Integer timestamp = DateTimeUtils.getNowTimeStamp();
        //购买团购
        Integer groupBuyTypeTip = 0;
        List<String> codes = groupBuyUseReDto.getGroupBuyUseCode();
        BmsVerRecord bmsVerRecord = null;
        List<BmsVerRecord> verRecords = bmsVerRecordService.getRecodeByCodes(groupBuyUseReDto.getGroupBuyUseCode());
        if(verRecords != null && verRecords.size() > 0){
            bmsVerRecord = verRecords.get(0);
            //检查类型
            Set<Integer> verType = verRecords.stream().map(BmsVerRecord::getVerType).collect(Collectors.toSet());
            if(verType.size() > 1){
                return ResultMapHelper.result(ResultCode.CODE_GROUP_BUY_NO_EQUEAL,ResultMsg.MSG_GROUP_BUY_NO_EQUEAL);
            }
            if(verRecords.size() != codes.size()){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_ORDER,ResultMsg.CODE_ORDER_GROUP_USE_NO_ORDER);
            }
            groupBuyTypeTip = bmsVerRecord.getVerType();
        }else {
            // TODO 补偿机制，向上兼容
            Map<String,Object> conditionMap = new LinkedHashMap<>();
            conditionMap.put("groupBuyCode_IN",new HashSet<>(codes));
            //conditionMap.put("status",Constants.GROUP_NO_USE);
            List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
            if(bmsDxGroupBuyUses.size() == codes.size()){
                BmsDxGroupBuyUse bmsDxGroupBuyUse = bmsDxGroupBuyUses.get(0);
                groupBuyTypeTip = 1;
                bmsVerRecord = new BmsVerRecord();
                bmsVerRecord.setOrderId(bmsDxGroupBuyUse.getOrderId());
                //return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_ORDER,ResultMsg.CODE_ORDER_GROUP_USE_NO_ORDER);
            }
            if(bmsDxGroupBuyUses.size() == Constants.COMMON_FLAG_FALSE_INT) {
                //领取团购
                conditionMap.clear();
                conditionMap.put("consumerCode_IN", new HashSet<>(codes));
                //conditionMap.put("status", Constants.GROUP_NO_USE);
                List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                if (bmsUserReceCoupons.size() == codes.size()) {
                    groupBuyTypeTip = 2;
                    for (BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons) {
                        bmsVerRecord = new BmsVerRecord();
                        bmsVerRecord.setReceId(bmsUserReceCoupon.getId());
                        verRecords.add(bmsVerRecord);
                    }
                    //return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_ORDER,ResultMsg.CODE_ORDER_GROUP_USE_NO_ORDER);
                }else {
                    return ResultMapHelper.result(CouponEnums.COUPON_NO_CAN_USE);
                }
            }
        }
        if(groupBuyTypeTip == 0){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_ORDER,ResultMsg.CODE_ORDER_GROUP_USE_NO_ORDER);
        }
        // TODO 开始核销
        GroupBuyUseReDto params = new GroupBuyUseReDto();
        if(groupBuyTypeTip == 1){
            //TODO 购买券
            params.setBusinessId(groupBuyUseReDto.getBusinessId());
            params.setOrderId(bmsVerRecord.getOrderId());
            params.setGroupBuyUseCodes(JSON.toJSONString(groupBuyUseReDto.getGroupBuyUseCode()));
            //券码核销
            params.setVerStatus(groupBuyUseReDto.getVerStatus());
            //购买券
            params.setVerWay(Constants.VER_WAY_ONE);
            params.setUserId(groupBuyUseReDto.getUserId());
            params.setVerCodeExtraWay(groupBuyUseReDto.getVerCodeExtraWay());
            Map<String,Object> retMap = businessUserVerGroupBuy(params);
            return retMap;
        }else if(groupBuyTypeTip == 2){
            //TODO 领取券
            Map<String,Object> conditionMap = new LinkedHashMap<>();
            conditionMap.put("id_IN",verRecords.stream().map(BmsVerRecord::getReceId).collect(Collectors.toSet()));
            List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
            //检验券的合法性
            if(!(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0)){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_IS_USE,ResultMsg.CODE_BUSINESS_COUPON_IS_USE);
            }
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                if(bmsUserReceCoupon.getBusinessId().intValue() != groupBuyUseReDto.getBusinessId().intValue()){
                    return ResultMapHelper.result(CouponEnums.COUPON_NO_CAN_USE);
                }
                if(bmsUserReceCoupon.getStatus() == Constants.IS_USE){
                    return ResultMapHelper.result(CouponEnums.COUPON_EXIST_USE);
                }else if(bmsUserReceCoupon.getStatus() == Constants.IS_OVER_EXPIRE){
                    return ResultMapHelper.result(CouponEnums.COUPON_EXPIRE);
                }
                if(timestamp >= DateTimeUtils.converDateToInterger(bmsUserReceCoupon.getExpireTime())){
                    bmsUserReceCoupon.setStatus(Constants.IS_OVER_EXPIRE);
                    bmsUserReceCouponService.getBaseDao().save(bmsUserReceCoupon);
                    return ResultMapHelper.result(CouponEnums.COUPON_EXPIRE);
                }
            }
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                bmsUserReceCoupon.setStatus(Constants.COMMON_FLAG_TRUE_INT);
                bmsUserReceCoupon.setUseTime(nowTime);
                bmsUserReceCoupon.setVerWay(groupBuyUseReDto.getVerStatus());
                bmsUserReceCoupon.setVerName(bmsUserBusinessService.
                        findNameInStoreByUserId(Integer.parseInt(groupBuyUseReDto.getUserId()),groupBuyUseReDto.getBusinessId()));
            }
            if(bmsUserReceCoupons.size() > 0){
                bmsUserReceCouponService.getBaseDao().saveAll(bmsUserReceCoupons);
                BmsCommonService.getApplicationContext().publishEvent(new UserReceEvent("receCouponVer",bmsUserReceCoupons));
                return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
            }
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
    }

    public void recordVerData(ReGroupUseLog reGroupUseLog, BmsDxOrder bmsDxOrder, Double total,
                              List<BmsDxGroupBuyUse> bmsDxGroupBuyUses){
        reGroupUseLog.setOrderId(bmsDxOrder.getId());
        Set<Integer> groupBuyUseIds = new HashSet<>();
        Set<String> groupBuyCodes = new HashSet<>();
        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
            groupBuyUseIds.add(bmsDxGroupBuyUse.getId());
            groupBuyCodes.add(bmsDxGroupBuyUse.getGroupBuyCode());
        }
        reGroupUseLog.setGroupBuyUseIds(JSON.toJSONString(groupBuyUseIds));
        reGroupUseLog.setGroupBuyUseCodes(JSON.toJSONString(groupBuyCodes));
        reGroupUseLog.setIsSettleSuccess(Constants.COMMON_FLAG_FALSE_INT);
        reGroupUseLog.setTotal(total);
        reGroupUseLog.setNewTime(new Date());
    }

    private void addGroupBuyUseEvent(BmsDxOrder bmsDxOrder,List<BmsDxGroupBuyUse> bmsDxGroupBuyUses) {
        BmsCommonService.getApplicationContext().publishEvent(new GroupBuyEvent("团购核销监听",bmsDxOrder,bmsDxGroupBuyUses));
    }

    /**
     * @Description 记录团购套餐
     * @Author: cfx
     * @Date: 2019/9/18
     */
    @Override
    public synchronized Map<String, Object> recordGroupBuyVisitNum(DxGroupBuyReDto dxGroupBuyReDto) {
        Integer id = dxGroupBuyReDto.getId();
        Optional<BmsDxGroupBuy> bmsDxGroupBuyOptional = bmsDxGroupBuyDao.findById(id);
        if(bmsDxGroupBuyOptional.isPresent()){
            BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyOptional.get();
            if(bmsDxGroupBuy.getStatus() == Constants.ONLINE_STATUS) {
                bmsDxGroupBuy.setViewsNum(bmsDxGroupBuy.getViewsNum() == null ? 1 : bmsDxGroupBuy.getViewsNum() + 1);
                bmsDxGroupBuyDao.save(bmsDxGroupBuy);
            }
        }
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> getGroupBuyPreferential(ParamsMap paramsMap) {
        //过滤只有开通uid的商家才能显示团购
        Set<Integer> businessIds = getStartPayUidBusiness();
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        Integer pageSize = paramsMap.getInteger("pageSize");
        List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
        if(businessIds.size() > 0) {
            bmsDxGroupBuys = bmsDxGroupBuyDao.findMostDiscountPreBuy(businessIds);
        }
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            if(StringUtils.isNotBlank(addrCity) && StringUtils.isNotBlank(addrDistrict)
                    && StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)){
                List<BmsDxGroupBuy> localBmsDxGroupBuys = getAllLocationGroupBuy(bmsDxGroupBuys,addrCity,addrDistrict,latitude,longitude);
                postHandGroupBuySortDis(localBmsDxGroupBuys);
                //补一下不足团购
                Integer endIndex = pageSize - localBmsDxGroupBuys.size();
                if(endIndex > bmsDxGroupBuys.size()){
                    endIndex = bmsDxGroupBuys.size();
                }
                final int startIndex = 0;
                for(int ii = 0;ii < endIndex;ii++){
                    BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuys.get(startIndex);
                    localBmsDxGroupBuys.add(bmsDxGroupBuy);
                    bmsDxGroupBuys.remove(startIndex);
                }
                bmsDxGroupBuys = localBmsDxGroupBuys;
            }
            if(pageSize > bmsDxGroupBuys.size()){
                pageSize = bmsDxGroupBuys.size();
            }
            bmsDxGroupBuys = bmsDxGroupBuys.subList(0,pageSize);
            postHandleBusiness(bmsDxGroupBuys);
            postHandleBusinessHavingMoreGroupBuy(bmsDxGroupBuys);
            postHandleDiscount(bmsDxGroupBuys);

            //处理图片字段
            bmsDxGroupBuys.forEach(v->{
                //如果团购小图为空则默认为groupPhotos
                if(!StringUtils.checkAnyNotNull(v.getGroupPhotosSmall())){
                    v.setGroupPhotosSmall(v.getGroupPhotos());
                }
                imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
                if(v.getBmsBusiness() != null){
                    imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

                }
                });
            imgPrefixService.pushSpliceField(bmsDxGroupBuys,"groupImg","cloudCoverUrl","groupPhotos","groupPhotosSmall");
        }
        return ResultMapHelper.success(bmsDxGroupBuys,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> getGroupBuyPreferential_V2(ParamsMap paramsMap) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("isExclusive",Constants.COMMON_FLAG_TRUE_INT);
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Integer pageNum = paramsMap.getInteger("pageNum");
        //寻找当前城市商家
        List<BmsDxGroupBuy> bmsDxGroupBuys = new LinkedList<>();
        Integer count = 0;
        if(StringUtils.isNotBlank(addrCity) && StringUtils.isNotBlank(addrDistrict)){
            bmsDxGroupBuys.addAll(getAllLocationPreGroupBuy(addrCity,addrDistrict,longitude,latitude, BmsCommonService.getPageable(pageNum,pageSize)));
            count = countAllLocationPreGroupBuy(addrCity,addrDistrict);
        }
        Map<String,Object> userData = new HashMap<>();
        userData.put("count",count);
        postHandleBusinessIgnoreBuyCoupon(bmsDxGroupBuys);
        postHandleDiscount(bmsDxGroupBuys);
        postHandleDistance(bmsDxGroupBuys,latitude,longitude);
        //处理图片字段
        imgPrefixService.pushSpliceField(bmsDxGroupBuys,"groupImg");
        bmsDxGroupBuys.forEach(v->{
            imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
            if(v.getBmsBusiness() != null){
                imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

            }
         });



        return ResultMapHelper.success(bmsDxGroupBuys,userData,ResultMsg.MSG_GET_SUCCESS);
    }

    /*public Map<String, Object> getGroupBuyPreferential_V2(ParamsMap paramsMap) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("isExclusive",Constants.COMMON_FLAG_TRUE_INT);
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Integer pageNum = paramsMap.getInteger("pageNum");
        //寻找当前城市商家
        List<BmsDxGroupBuy> bmsDxGroupBuys = new LinkedList<>();
        Integer count = 0;
        Set<Integer> businessIds = new HashSet<>();
        if(StringUtils.isNotBlank(addrCity) && StringUtils.isNotBlank(addrDistrict)){
            businessIds.addAll(getAllLocationGroupBuy(addrCity,addrDistrict));
        }
        Map<String,Object> userData = new HashMap<>();

        boolean isCustomPage = true;
        if(businessIds.size() > 0){
            conditionMap.put("businessId_IN",businessIds);
            bmsDxGroupBuys.addAll(bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap)));
            count = bmsDxGroupBuys.size();
        }else {
            *//*if(payBusinessIds.size() == 0){
                payBusinessIds.add(Constants.NOT_IN);
            }
            isCustomPage = false;
            conditionMap.put("businessId_IN",payBusinessIds);
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"sellNum");
            Page<BmsDxGroupBuy> bmsDxGroupBuyPage = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap),pageable);
            bmsDxGroupBuys.addAll(bmsDxGroupBuyPage.getContent());
            userData.put("count",bmsDxGroupBuys.size());*//*
        }
        postHandleBusinessIgnoreBuyCoupon(bmsDxGroupBuys);
        postHandleDiscount(bmsDxGroupBuys);
        postHandleDistance(bmsDxGroupBuys,latitude,longitude);
        postHandGroupBuySortDis(bmsDxGroupBuys);
        //手动分页
        if(isCustomPage) {
            bmsDxGroupBuys = bmsCommonService.customPage(pageNum, pageSize, bmsDxGroupBuys);
        }
        userData.put("count",count);
        return ResultMapHelper.success(bmsDxGroupBuys,userData,ResultMsg.MSG_GET_SUCCESS);
    }*/


    public void postHandleDistance(List<BmsDxGroupBuy> bmsDxGroupBuys,String latitude,String longitude){
        if(StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
            if (bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0) {
                for (BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys) {
                    BusinessRpDto business = bmsDxGroupBuy.getBmsBusiness();
                    if(StringUtils.isNotBlank(business.getLatitude()) && StringUtils.isNotBlank(business.getLongitude())) {
                        double lat = Double.parseDouble(business.getLatitude());
                        double lnt = Double.parseDouble(business.getLongitude());
                        double distance = LocationUtils.getDistance(lat, lnt, Double.parseDouble(latitude), Double.parseDouble(longitude));
                        business.setDistance(distance);
                    }
                }
            }
        }
    }

    public Set<Integer> getAllLocationGroupBuy(String addrCity,String addrDistrict){
        Set<Integer> ids = new HashSet<>();
        List<Map<String,Object>> groupBuys = bmsDxGroupBuyDao.findLocalGroupBuy(addrCity,addrDistrict);
        if(groupBuys != null && groupBuys.size() > 0){
            for(Map<String,Object> g : groupBuys ){
                ids.add(Integer.parseInt(g.get("id").toString()));
            }
        }
        return ids;
    }

    public List<BmsDxGroupBuy> getAllLocationPreGroupBuy(String addrCity,String addrDistrict,
                                                         String lnt,String lat,Pageable pageable){
        return bmsDxGroupBuyDao.findLocalPreGroupBuy(addrCity,addrDistrict,lnt,lat,pageable);
    }

    public Integer countAllLocationPreGroupBuy(String addrCity,String addrDistrict){
        return bmsDxGroupBuyDao.countLocalPreGroupBuy(addrCity,addrDistrict);
    }

    public List<BmsDxGroupBuy> getAllLocationLimitGroupBuy(String addrCity,String addrDistrict,
                                                           String lnt,String lat,Pageable pageable){
        return bmsDxGroupBuyDao.findLocalLimitGroupBuy(addrCity,addrDistrict,lnt,lat,pageable);
    }

    public Integer countAllLocationLimitGroupBuy(String addrCity, String addrDistrict) {
        return bmsDxGroupBuyDao.countLocalLimitGroupBuy(addrCity,addrDistrict);
    }

    public Set<Integer> getAllLocationGroupBuy(String addrCity){
        Set<Integer> ids = new HashSet<>();
        List<Map<String,Object>> groupBuys = bmsDxGroupBuyDao.findLocalGroupBuy(addrCity);
        if(groupBuys != null && groupBuys.size() > 0){
            for(Map<String,Object> g : groupBuys ){
                ids.add(Integer.parseInt(g.get("id").toString()));
            }
        }
        return ids;
    }

    public List<BmsDxGroupBuy> getAllLocationGroupBuy(List<BmsDxGroupBuy> bmsDxGroupBuys,
                                                      String addrCity, String addrDistrict, String latitude, String longitude){
        List<BmsDxGroupBuy> bmsDxGroupBuyList = new LinkedList<>();
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0) {
            Map<Integer, List<BmsDxGroupBuy>> groupMap = new HashMap<>();
            for (BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys) {
                if (!groupMap.containsKey(bmsDxGroupBuy.getBusinessId())) {
                    groupMap.put(bmsDxGroupBuy.getBusinessId(), new ArrayList<>());
                }
                groupMap.get(bmsDxGroupBuy.getBusinessId()).add(bmsDxGroupBuy);
            }
            Set<Integer> businessIds = bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getBusinessId).collect(Collectors.toSet());
            Map<String, Object> businessSearchMap = new HashMap<>();
            businessSearchMap.put("id_IN", businessIds);
            businessSearchMap.put("isDelete", Constants.COMMON_FLAG_FALSE_INT);
            businessSearchMap.put("isUnload", Constants.COMMON_FLAG_FALSE_INT);
            if(StringUtils.isNotBlank(addrCity)) {
                businessSearchMap.put("addrCity", addrCity);
            }
            if(StringUtils.isNotBlank(addrDistrict)) {
                businessSearchMap.put("addrDistrict", addrDistrict);
            }
            List<BmsBusiness> bmsBusinesses = bmsBusinessService.getBaseDao().findAll(new SpecificationUtils(businessSearchMap));
            if (bmsBusinesses != null && bmsBusinesses.size() > 0) {
                for (BmsBusiness business : bmsBusinesses) {
                    if (StringUtils.isNotBlank(business.getLatitude()) && StringUtils.isNotBlank(business.getLongitude())) {
                        double lat = Double.parseDouble(business.getLatitude());
                        double lnt = Double.parseDouble(business.getLongitude());
                        double distance = LocationUtils.getDistance(lat, lnt, Double.parseDouble(latitude), Double.parseDouble(longitude));
                        distance = ArithUtil.round(distance,2);
                        Integer businessId = business.getId();
                        if (groupMap.containsKey(businessId)) {
                            List<BmsDxGroupBuy> buys = groupMap.get(businessId);
                            for (BmsDxGroupBuy bmsDxGroupBuy : buys) {
                                BusinessRpDto businessRpDto = new BusinessRpDto();
                                business.setDistance(distance);
                                BeanUtils.copyProperties(business, businessRpDto);
                                bmsDxGroupBuy.setBmsBusiness(businessRpDto);
                            }
                            bmsDxGroupBuyList.addAll(buys);
                        }
                    }
                }
            }
        }
        return bmsDxGroupBuyList;
    }

    @Override
    public Map<String, Object> getGroupBuyPreferentialMore(ParamsMap paramsMap) {
        Set<Integer> businessIds = getStartPayUidBusiness();
        List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
        Map<String, Object> userDataMap = new HashMap<>();
        userDataMap.put("count",Constants.COMMON_FLAG_FALSE_INT);
        if(businessIds.size() > 0) {
            Integer pageSize = paramsMap.getInteger("pageSize");
            Integer pageNum = paramsMap.getInteger("pageNum");
            String latitude = paramsMap.getString("latitude");
            String longitude = paramsMap.getString("longitude");
            String addrCity = paramsMap.getString("addrCity");
            String addrDistrict = paramsMap.getString("addrDistrict");
            Map<String, Object> conditionMap = new HashMap<>();
            conditionMap.put("isDelete", Constants.COMMON_FLAG_FALSE_INT);
            conditionMap.put("status", Constants.COMMON_FLAG_TRUE_INT);
            conditionMap.put("isExclusive", Constants.COMMON_FLAG_TRUE_INT);
            conditionMap.put("businessId_IN", businessIds);
            if (StringUtils.isNotBlank(addrCity) && StringUtils.isNotBlank(addrDistrict)
                    && StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
                bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap));
                bmsDxGroupBuys = getAllLocationGroupBuy(bmsDxGroupBuys, addrCity, addrDistrict, latitude, longitude);
                postHandGroupBuySortDis(bmsDxGroupBuys);
                bmsDxGroupBuys = costomPage(pageNum, pageSize, bmsDxGroupBuys);
                userDataMap.put("count", bmsDxGroupBuyDao.count(new SpecificationUtils(conditionMap)));
            } else {
                Pageable pageable = BmsCommonService.getPageable(pageNum,
                        pageSize, Sort.Direction.DESC, "sellNum");
                Page<BmsDxGroupBuy> bmsDxGroupBuyPage = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap), pageable);
                bmsDxGroupBuys = bmsDxGroupBuyPage.getContent();
                userDataMap.put("count", bmsDxGroupBuyPage.getTotalElements());
                postHandleBusiness(bmsDxGroupBuys);
                postHandleGroupBuyDistince(bmsDxGroupBuys, latitude, longitude);
            }
        }
        postHandleDiscount(bmsDxGroupBuys);

        //处理图片字段
        imgPrefixService.pushSpliceField(bmsDxGroupBuys,"groupImg","cloudCoverUrl");
        bmsDxGroupBuys.forEach(v->{
            imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
            if(v.getBmsBusiness() != null){
                imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

            }});
        return ResultMapHelper.success(bmsDxGroupBuys,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    private void postHandleGroupBuyDistince(List<BmsDxGroupBuy> bmsDxGroupBuys,String lat,String lng) {
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            List<BusinessRpDto> bmsBusinesses = new ArrayList<>();
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                BusinessRpDto bmsBusinessRpDto = bmsDxGroupBuy.getBmsBusiness();
                bmsBusinesses.add(bmsBusinessRpDto);
                this.calculatedDistance(bmsBusinesses,lat,lng);
            }
        }
    }

    public void calculatedDistance(List<BusinessRpDto> bmsBusinesses, String latitude, String longitude) {
        if(StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
            if (bmsBusinesses != null && bmsBusinesses.size() > 0) {
                for (BusinessRpDto businessRpDto : bmsBusinesses) {
                    if(StringUtils.isNotBlank(businessRpDto.getLatitude()) && StringUtils.isNotBlank(businessRpDto.getLongitude())) {
                        double lat = Double.parseDouble(businessRpDto.getLatitude());
                        double lnt = Double.parseDouble(businessRpDto.getLongitude());
                        double distance = Math.ceil(LocationUtils.getDistance(lat, lnt, Double.parseDouble(latitude), Double.parseDouble(longitude)));
                        businessRpDto.setDistance(distance);
                    }
                }
            }
        }
    }

    @Override
    public Map<String, Object> getGroupBuyDetail(ParamsMap paramsMap) {
        CheckUserBo checkUserBo = RequestParamUtils.checkUserBo();
        //默认使用设备标识
        Integer userIdentify = null;
        if(checkUserBo.getCheckStatus().equals(ResultCode.CODE_NORMAL)){
            userIdentify = Integer.parseInt(checkUserBo.getUserId());
        }
        Integer groupBuyId = paramsMap.getInteger("id");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("id",groupBuyId);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        //conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap));
        if(!(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY,ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
        }
        postHandleBusiness(bmsDxGroupBuys);
        postHandleDiscount(bmsDxGroupBuys);
        postHandleGroupBuyDistince(bmsDxGroupBuys,latitude,longitude);
        postHandleGroupContent(bmsDxGroupBuys,true);
        //更新该团购的浏览量
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuys.get(0);
        entityManager.unwrap(Session.class).evict(bmsDxGroupBuy);
        postHandleGroupGif(bmsDxGroupBuys);
        Map<String,Object> userData = new HashedMap();
        userData.put("serverTime",new Date());
        BmsCommonService.getApplicationContext().publishEvent(new GetGroupBuyDetailEvent("groupBuyDetail",bmsDxGroupBuy,userIdentify));


        //处理图片字段

        bmsDxGroupBuys.forEach(v->{
            //如果团购小图为空则默认为groupPhotos
            if(!StringUtils.checkAnyNotNull(v.getGroupPhotosSmall())){
                v.setGroupPhotosSmall(v.getGroupPhotos());
            }
            imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
            if(v.getBmsBusiness() != null){
                imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

            }});
        imgPrefixService.pushSpliceField(bmsDxGroupBuys,"groupImg","cloudCoverUrl","groupPhotos","groupPhotosSmall");
        return ResultMapHelper.success(bmsDxGroupBuys.get(0),userData,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> getGroupBuyMore(ParamsMap paramsMap) {
        Set<Integer> businessIds = getStartPayUidBusiness();
        final int auto = 3;
        Integer start = paramsMap.getInteger("start");
        Integer end = paramsMap.getInteger("end");
        List<BmsDxGroupBuy> resultList = new LinkedList<>();
        if(businessIds.size() > 0){
            String addrCity = paramsMap.getString("addrCity");
            String addrDistrict = paramsMap.getString("addrDistrict");
            String latitude = paramsMap.getString("latitude");
            String longitude = paramsMap.getString("longitude");
            //String devId = paramsMap.getString("devId");
            Map<String,Object> conditionMap = new HashMap<>();
            conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
            conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
            conditionMap.put("isExclusive",Constants.COMMON_FLAG_FALSE_INT);
            conditionMap.put("businessId_IN",businessIds);
            //Sort sort = Sort.by(Sort.Direction.DESC,"sellNum");
            List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
            if(StringUtils.isNotBlank(addrCity) && StringUtils.isNotBlank(addrDistrict)
                    && StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
                if(businessIds.size() > 0){
                    bmsDxGroupBuys = bmsDxGroupBuyDao.findOrdinaryMoreGroupBuy(businessIds);
                }
                resultList = getAllLocationGroupBuy(bmsDxGroupBuys,addrCity,addrDistrict,latitude,longitude);
                Integer pageNum = (end - 3) / 3 + 1;
                Integer pageSize = 10;
                if(resultList.size() > 0) {
                    postHandGroupBuySortDis(resultList);
                    resultList = costomPage(pageNum,pageSize,resultList);
                }
            }else {
                hanleNoData(resultList,businessIds,end);
            }
        }
        Map<String,Object> userData = new HashMap<>();
        userData.put("isLastPage",Constants.COMMON_FLAG_FALSE_INT);
        userData.put("start",start);
        userData.put("end",end);
        if(resultList.size() == 0){
            userData.put("isLastPage",Constants.COMMON_FLAG_TRUE_INT);
        }else {
            userData.put("start",start + auto);
            userData.put("end",end + auto);
        }
        //处理图片字段
        resultList.forEach(v->{
            //如果团购小图为空则默认为groupPhotos
            if(!StringUtils.checkAnyNotNull(v.getGroupPhotosSmall())){
                v.setGroupPhotosSmall(v.getGroupPhotos());
            }
            imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
            if(v.getBmsBusiness() != null){
                imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

            }});
        imgPrefixService.pushSpliceField(resultList,"groupImg","cloudCoverUrl","groupPhotos","groupPhotosSmall");

        return ResultMapHelper.success(resultList,userData,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> getLimitBuyGroupBuy(ParamsMap paramsMap) {
        Set<Integer> businessIds = getStartPayUidBusiness();
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        Integer pageSize = paramsMap.getInteger("pageSize");
        if(businessIds.size() == 0){
            businessIds.add(Constants.COMMON_FLAG_FALSE_INT);
        }
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findMostDiscountLimitBuy(businessIds);
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            postHandleBusiness(bmsDxGroupBuys);
            postHandleBusinessHavingMoreGroupBuy(bmsDxGroupBuys);
            postHandleDiscount(bmsDxGroupBuys);
            if(StringUtils.isNotBlank(addrCity) && StringUtils.isNotBlank(addrDistrict)
                    && StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)){
                bmsDxGroupBuys = getAllLocationGroupBuy(bmsDxGroupBuys,addrCity,addrDistrict,latitude,longitude);
                postHandGroupBuySortDis(bmsDxGroupBuys);
            }
            if(pageSize > bmsDxGroupBuys.size()){
                pageSize = bmsDxGroupBuys.size();
            }
            bmsDxGroupBuys = bmsDxGroupBuys.subList(0,pageSize);
            bmsDxGroupBuyDao.saveAll(bmsDxGroupBuys);
        }
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("serverTime",new Date());

        //处理图片字段
        bmsDxGroupBuys.forEach(v->{
            //如果团购小图为空则默认为groupPhotos
            if(!StringUtils.checkAnyNotNull(v.getGroupPhotosSmall())){
                v.setGroupPhotosSmall(v.getGroupPhotos());
            }
            imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
            if(v.getBmsBusiness() != null){
                imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

            }});
        imgPrefixService.pushSpliceField(bmsDxGroupBuys,"groupImg","cloudCoverUrl","groupPhotos","groupPhotosSmall");

        return ResultMapHelper.success(bmsDxGroupBuys,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    /*@Override
    public Map<String, Object> getLimitBuyGroupBuy_V2(ParamsMap paramsMap) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("isTimeLimit",Constants.COMMON_FLAG_TRUE_INT);
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Integer pageNum = paramsMap.getInteger("pageNum");
        //寻找当前城市商家
        List<BmsDxGroupBuy> bmsDxGroupBuys = new LinkedList<>();
        Map<String,Object> userData = new HashMap<>();
        boolean isCustomPage = true;
        Integer count = 0;
        if(StringUtils.isNotBlank(addrCity) && StringUtils.isNotBlank(addrDistrict)){
            bmsDxGroupBuys.addAll(getAllLocationLimitGroupBuy(addrCity,addrDistrict,longitude,latitude,BmsCommonService.getPageable(pageNum,pageSize)));
            count = countAllLocationLimitGroupBuy(addrCity,addrDistrict);
        }
        userData.put("count",count);
        *//*if(businessIds.size() > 0){
            conditionMap.put("businessId_IN",businessIds);
            bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap)));

        }else {
            *//**//*payBusinessIds.clear();
            payBusinessIds.add(Constants.NOT_IN);
            isCustomPage = false;
            conditionMap.put("businessId_IN",payBusinessIds);
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"sellNum");
            Page<BmsDxGroupBuy> bmsDxGroupBuyPage = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap),pageable);
            bmsDxGroupBuys.addAll(bmsDxGroupBuyPage.getContent());
            userData.put("count",bmsDxGroupBuyPage.getTotalElements());*//**//*
            userData.put("count",bmsDxGroupBuys.size());
        }*//*
        postHandleBusinessIgnoreBuyCoupon(bmsDxGroupBuys);
        postHandleDiscount(bmsDxGroupBuys);
        postHandleDistance(bmsDxGroupBuys,latitude,longitude);
        //postHandGroupBuySortDis(bmsDxGroupBuys);
        //手动分页
        *//*if(isCustomPage) {
            bmsDxGroupBuys = bmsCommonService.customPage(pageNum, pageSize, bmsDxGroupBuys);
        }*//*
        userData.put("serverTime",new Date());
        return ResultMapHelper.success(bmsDxGroupBuys,userData,ResultMsg.MSG_GET_SUCCESS);
    }*/

    @Override
    public Map<String, Object> getLimitBuyGroupBuy_V2(ParamsMap paramsMap) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("isTimeLimit",Constants.COMMON_FLAG_TRUE_INT);
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Integer pageNum = paramsMap.getInteger("pageNum");
        //寻找当前城市商家
        List<BmsDxGroupBuy> bmsDxGroupBuys = new LinkedList<>();
        Map<String,Object> userData = new HashMap<>();
        boolean isCustomPage = true;
        Integer count = 0;
        Set<Integer> businessIds = new HashSet<>();
        if(StringUtils.isNotBlank(addrCity) && StringUtils.isNotBlank(addrDistrict)){
            businessIds.addAll(getAllLocationGroupBuy(addrCity,addrDistrict));
            //count = countAllLocationLimitGroupBuy(addrCity,addrDistrict);
        }

        if(businessIds.size() > 0){
            conditionMap.put("businessId_IN",businessIds);
            bmsDxGroupBuys.addAll(bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap)));

        }else {
            isCustomPage = false;
            /*conditionMap.put("businessId_IN",payBusinessIds);
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"sellNum");
            Page<BmsDxGroupBuy> bmsDxGroupBuyPage = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap),pageable);
            bmsDxGroupBuys.addAll(bmsDxGroupBuyPage.getContent());
            userData.put("count",bmsDxGroupBuyPage.getTotalElements());
            userData.put("count",bmsDxGroupBuys.size());*/
        }
        postHandleBusinessIgnoreBuyCoupon(bmsDxGroupBuys);
        postHandleDiscount(bmsDxGroupBuys);
        postHandleDistance(bmsDxGroupBuys,latitude,longitude);
        postHandGroupBuySortDis(bmsDxGroupBuys);
        //手动分页
        if(isCustomPage) {
            bmsDxGroupBuys = bmsCommonService.customPage(pageNum, pageSize, bmsDxGroupBuys);
        }
        userData.put("count",count);
        userData.put("serverTime",new Date());
        List<GetAllGroupBuy_v2Vo> getAllGroupBuy_v2Vos = postHandleCleanData(bmsDxGroupBuys);
        getAllGroupBuy_v2Vos.stream().forEach(v->{
            imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
            if(v.getBmsBusiness() != null){
                imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

            }});
        imgPrefixService.pushSpliceField(getAllGroupBuy_v2Vos,"groupImg");
        return ResultMapHelper.success(getAllGroupBuy_v2Vos,userData,ResultMsg.MSG_GET_SUCCESS);
    }




    @Override
    public Map<String, Object> getBusinessMoreGroupBuy(ParamsMap paramsMap) {
        Integer businessId = paramsMap.getInteger("businessId");
        Integer groupBuyId = paramsMap.getInteger("groupBuyId");
        Integer pageSize = paramsMap.getInteger("pageSize");
        if(pageSize == null){
            pageSize = 10;
        }
        //找出除该团购外的其他团购列表
        Pageable pageable = BmsCommonService.getPageable(1,pageSize);
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("businessId",businessId);
        conditionMap.put("id_NEQ",groupBuyId);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap),pageable).getContent();
        //处理图片字段
        bmsDxGroupBuys.forEach(v->{
            //如果团购小图为空则默认为groupPhotos
            if(!StringUtils.checkAnyNotNull(v.getGroupPhotosSmall())){
                v.setGroupPhotosSmall(v.getGroupPhotos());
            }
            imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
            if(v.getBmsBusiness() != null){
                imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

            }});
        imgPrefixService.pushSpliceField(bmsDxGroupBuys,"groupImg","cloudCoverUrl","groupPhotos","groupPhotosSmall");

        return ResultMapHelper.success(bmsDxGroupBuys,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> getAllGroupBuy(ParamsMap paramsMap) {
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        Integer client = requestHeaderData.getInteger("client");
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Integer pageNum = paramsMap.getInteger("pageNum");
        if(StringUtils.isBlank(addrCity) && StringUtils.isBlank(addrDistrict)){
            addrCity = "珠海市";
            addrDistrict = "香洲区";
        }
        //智能排序
        final int SORT_RULE_ONE = 1;
        //折扣优先
        final int SORT_RULE_TWO = 2;
        //人气优先
        final int SORT_RULE_THREE = 3;
        //距离优先
        final int SORT_RULE_FOUR = 4;
        //低价优先
        final int SORT_RULE_FIVE = 5;
        //高价优先
        final int SORT_RULE_SIX = 6;
        Map<String,Object> userDataMap = new HashMap<>();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        Set<Integer> groupTypes = new HashSet<>(Arrays.asList(new Integer[]{BmsDxGroupBuyService.GROUP_TYPE_GEN
                , BmsDxGroupBuyService.GROUP_TYPE_TETE}));
        if(client == Constants.SMALL_PROGRAM) {
            groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_BARGAIN);
        }
        conditionMap.put("groupType_IN",groupTypes);
        //在有输入文本的情况下
        Map<String, Object> businessCondition = new HashMap<>();
        businessCondition.put("isUnload", Constants.COMMON_FLAG_FALSE_INT);
        businessCondition.put("isDelete", Constants.COMMON_FLAG_FALSE_INT);
        businessCondition.put("isAuth",Constants.COMMON_FLAG_TRUE_INT);
        String searchText = paramsMap.getStringSimple("searchText");
        boolean isRecommend = true;
        /*if(StringUtils.isNotBlank(searchText)){
            businessCondition.put("vendorName_LIKE",searchText);
        }*/
        //有选择标签的情况下
        if(paramsMap.containsKey("typeAndLabel")){
            //List<Map<String,Object>>  JSON.parse(t)
            //Set<Integer> typeIds = new HashSet<>();
            JSONArray jsonArray = JSON.parseArray(paramsMap.getString("typeAndLabel"));
            for(int ii = 0;ii < jsonArray.size();ii++){
                Map<String,Object> typeLabel = jsonArray.getJSONObject(ii);
                Integer typeId = Integer.parseInt(typeLabel.get("typeId").toString());
                if(typeLabel.containsKey("labelIds")){
                    List<Integer> labelIds = (List<Integer>) typeLabel.get("labelIds");
                    if(labelIds.size() > 0){
                        List<BmsBusinessLabel> bmsBusinessLabels = bmsBusinessLabelService.getBaseDao().findByIdInAndIsDelete(new HashSet<>(labelIds), Constants.COMMON_FLAG_FALSE_INT);
                        if (bmsBusinessLabels != null && bmsBusinessLabels.size() > 0) {
                            Set<String> labelNames = bmsBusinessLabels.stream().map(BmsBusinessLabel::getLabelName).collect(Collectors.toSet());
                            businessCondition.put("label_IN", labelNames);
                            /*businessCondition.put("isUnload", Constants.COMMON_FLAG_FALSE_INT);
                            businessCondition.put("isDelete", Constants.COMMON_FLAG_FALSE_INT);
                            businessCondition.put("isAuth",Constants.COMMON_FLAG_TRUE_INT);
                            List<BmsBusiness> bmsBusinesses = bmsBusinessService.getBaseDao().findAll(new SpecificationUtils(businessCondition));
                            if (bmsBusinesses != null && bmsBusinesses.size() > 0) {
                                businessIds.addAll(bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet()));
                            }else {
                                businessIds.add(Constants.NOT_INT);
                            }*/
                        }
                    }else {
                        Set<Integer> btIds = new HashSet<>();
                        btIds.addAll(bmsBusinessTypeRelationService.findAuthBusinessIdInType(typeId));
                        if(btIds.size() > 0){
                            businessCondition.put("id_IN",btIds);
                        }else {
                            btIds.add(Constants.NOT_IN);
                            businessCondition.put("id_IN",btIds);
                        }
                    }
                }else {
                    Set<Integer> btIds = new HashSet<>();
                    btIds.addAll(bmsBusinessTypeRelationService.findAuthBusinessIdInType(typeId));
                    if(btIds.size() > 0){
                        businessCondition.put("id_IN",btIds);
                    }else {
                        btIds.add(Constants.NOT_IN);
                        businessCondition.put("id_IN",btIds);
                    }
                }
            }
            /*if(businessIds.size() > 0){
                conditionMap.put("businessId_IN", businessIds);
            }*/
        }else {
            if (paramsMap.containsKey("labelIds")) {
                String labelArgs = paramsMap.getString("labelIds");
                if (StringUtils.isNotBlank(labelArgs)) {
                    List<Integer> labelIds = JSON.parseArray(labelArgs, Integer.class);
                    if (labelIds.size() > 0) {
                        Set<Integer> labelSet = new HashSet<>(labelIds);
                        List<BmsBusinessLabel> bmsBusinessLabels = bmsBusinessLabelService.getBaseDao().findByIdInAndIsDelete(labelSet, Constants.COMMON_FLAG_FALSE_INT);
                        if (bmsBusinessLabels != null && bmsBusinessLabels.size() > 0) {
                            Set<String> labelNames = bmsBusinessLabels.stream().map(BmsBusinessLabel::getLabelName).collect(Collectors.toSet());
                            if (labelNames.size() > 0) {
                                //Map<String, Object> businessCondition = new HashMap<>();
                                businessCondition.put("label_IN", labelNames);
                                /*businessCondition.put("isUnload", Constants.COMMON_FLAG_FALSE_INT);
                                businessCondition.put("isDelete", Constants.COMMON_FLAG_FALSE_INT);
                                businessCondition.put("isAuth",Constants.COMMON_FLAG_TRUE_INT);
                                List<BmsBusiness> bmsBusinesses = bmsBusinessService.getBaseDao().findAll(new SpecificationUtils(businessCondition));
                                if (bmsBusinesses != null && bmsBusinesses.size() > 0) {
                                    conditionMap.put("businessId_IN", bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet()));
                                }*/
                            }
                        }
                    }
                }
            }
        }
        //有商圈的情况下
        if(paramsMap.containsKey("businessCircles") && StringUtils.checkNullAndEmpty(paramsMap.get("businessCircles"))){
            String businessCircle = paramsMap.getString("businessCircles");
            Map<String,Object> circleCondition = (Map<String, Object>) JSON.parse(businessCircle);
            Set<Integer> businessIds = new HashSet<>();
            boolean isNotHaveCirId = true;
            //筛选出对应的地区的店铺
            String addrParentCity = circleCondition.get("addrParentCity").toString();
            String buinessCirCity = circleCondition.get("addCity").toString();
            if(!("热门商圈".equals(addrDistrict))){
                //将定位覆盖
                addrCity = "";
                addrDistrict = "";
            }
            if(circleCondition.containsKey("cirId")){
                JSONArray jsonArray = (JSONArray) circleCondition.get("cirId");
                if(jsonArray.size() > 0) {
                    //筛选出商圈对应的店铺id
                    isNotHaveCirId = false;
                    businessIds = bmsBusinessService.findBusinessIdByCircle(jsonArray.toJSONString());
                }
            }
            if(isNotHaveCirId){
                if("热门商圈".equals(buinessCirCity)){
                    Set<Integer> areaIds = bmsBusinessAreaService.findHotByAddr(addrParentCity);
                    if(areaIds.size() > 0){
                        Set<String> areas = new HashSet<>();
                        for(Integer area : areaIds){
                            areas.add(area.toString());
                        }
                        businessIds = bmsBusinessService.findBusinessIdByCircle(JSON.toJSONString(areas));
                    }
                }else {
                    businessIds = bmsBusinessService.findBusinessIdByAddr(addrParentCity,buinessCirCity);
                }
            }
            Set<Integer> bIds = new HashSet<>();
            if(businessIds.size() > 0){
                if(businessCondition.containsKey("id_IN")){
                    Set<Integer> existIds = (Set<Integer>) businessCondition.get("id_IN");
                    bIds.addAll(existIds);
                    bIds.retainAll(businessIds);
                    if(bIds.size() > 0){
                        businessCondition.put("id_IN",bIds);
                    }else {
                        bIds.add(Constants.NOT_IN);
                        businessCondition.put("id_IN",bIds);
                    }
                }else {
                    businessCondition.put("id_IN",businessIds);
                }
            }else {
                bIds.add(Constants.NOT_IN);
                businessCondition.put("id_IN",bIds);
            }
        }
        //统一查询
        List<BmsBusiness> bmsBusinesses = bmsBusinessService.getBaseDao().findAll(new SpecificationUtils(businessCondition));
        if(bmsBusinesses != null && bmsBusinesses.size() > 0){
            conditionMap.put("businessId_IN",bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet()));
        }else {
            Set<Integer> noBusinessIds = new HashSet<>();
            noBusinessIds.add(Constants.NOT_IN);
            conditionMap.put("businessId_IN", noBusinessIds);
            //不推荐
            isRecommend = false;
        }
        Set<Integer> payBusinessIds = getStartPayUidBusiness();
        Set<Integer> businessIds = new HashSet<>();
        if(StringUtils.isNotBlank(addrCity) && StringUtils.isNotBlank(addrDistrict)){
            Set<Integer> buIds = getAllLocationGroupBuy(addrCity,addrDistrict);
            if(buIds.size() > 0){
                for(Integer b : buIds){
                    if(payBusinessIds.contains(b)){
                        businessIds.add(b);
                    }
                }
            }
        }else if(StringUtils.isNotBlank(addrCity)){
            Set<Integer> buIds = getAllLocationGroupBuy(addrCity);
            if(buIds.size() > 0){
                for(Integer b : buIds){
                    if(payBusinessIds.contains(b)){
                        businessIds.add(b);
                    }
                }
            }
        } else {
            if(bmsBusinesses.size() > 0) {
                businessIds.addAll(bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet()));
            }
        }
        if(businessIds.size() == 0){
            businessIds.add(Constants.COMMON_FLAG_FALSE_INT);
            conditionMap.put("businessId_IN",businessIds);
        }else {
            if(conditionMap.containsKey("businessId_IN")){
                Set<Integer> bsIds = (Set<Integer>) conditionMap.get("businessId_IN");
                Set<Integer> cnBsIds = new HashSet<>();
                if(bsIds.size() > 0){
                    for(Integer b : bsIds){
                        if(businessIds.contains(b)){
                            cnBsIds.add(b);
                        }
                    }
                }
                if(cnBsIds.size() == 0){
                    cnBsIds.add(Constants.COMMON_FLAG_FALSE_INT);
                }
                conditionMap.put("businessId_IN",cnBsIds);
            }else {
                conditionMap.put("businessId_IN",businessIds);
            }
        }
        boolean isHaveDiscountDremoval = true;
        //排序规则
        Sort sort = Sort.by(Sort.Direction.ASC,"id");
        //排序规则
        Integer sortRule = paramsMap.getInteger("sortRule");
        //是否独家
        Set<Integer> groupIdsSet = new HashSet<>();
        Integer isExclusive = paramsMap.getInteger("isExclusive");
        //是否限时
        Integer isTimeLimit = paramsMap.getInteger("isTimeLimit");
        //是否是砍价团购
        Integer isBargainGroupBuy = paramsMap.getInteger("isBargainGroupBuy");
        //是否独家
        int haveCount = 0;
        if(isExclusive != null && isExclusive == Constants.COMMON_FLAG_TRUE_INT){
            //conditionMap.put("isExclusive",Constants.COMMON_FLAG_TRUE_INT);
            groupIdsSet.addAll(this.getIsExclusiveGroupBuy());
            haveCount++;
        }
        //是否限时
        if(isTimeLimit != null && isTimeLimit == Constants.COMMON_FLAG_TRUE_INT){
            //conditionMap.put("isTimeLimit",Constants.COMMON_FLAG_TRUE_INT);
            groupIdsSet.addAll(this.getIsTimeLimitGroupBuy());
            haveCount++;
        }
        //是否砍价
        if(isBargainGroupBuy != null && isBargainGroupBuy == Constants.COMMON_FLAG_TRUE_INT){
            //conditionMap.put("groupType",Constants.GROUP_TYPE_BARGAIN);
            groupIdsSet.addAll(this.getIsBargainGroupBuy());
            haveCount++;
        }
        //是否低于5折
        Integer isLessthanFive = paramsMap.getInteger("isLessthanFive");
        if(isLessthanFive != null && isLessthanFive == Constants.COMMON_FLAG_TRUE_INT){
            final Double FIVE_DISCOUNT = 5d;
            //conditionMap.put("discount_LTT",FIVE_DISCOUNT);
            groupIdsSet.addAll(this.getLessDiscountGroupBuy(FIVE_DISCOUNT));
            haveCount++;
        }
        Set<Integer> speIds = new HashSet<>();
        if(StringUtils.isNotBlank(searchText)){
            haveCount++;
            isHaveDiscountDremoval = false;
            //筛选符合条件的searchText的店铺下的团购id（折扣去重）
            //筛选符合条件的团购id（店铺去重）
            Set<Integer> groupNameIds = new HashSet<>();
            groupNameIds.addAll(this.findGroupNameGroupBuyIds(searchText));
            groupNameIds.addAll(this.getGroupBuyIdsByVendorNameDistinct(searchText));
            if(groupIdsSet.size() > 0) {
                Set<Integer> resultIds = new HashSet<>();
                if(groupNameIds.size() > 0){
                    for(Integer id : groupNameIds){
                        if(groupIdsSet.contains(id)){
                            resultIds.add(id);
                        }
                    }
                }
                if(resultIds.size() > 0){
                    groupIdsSet = resultIds;
                }
            }else{
                groupIdsSet = groupNameIds;
            }
        }
        if(haveCount > 0) {
            if (groupIdsSet.size() > 0) {
                conditionMap.put("id_IN", groupIdsSet);
            }else {
                groupIdsSet.add(Constants.NOT_IN);
                conditionMap.put("id_IN", groupIdsSet);
            }
        }
        //查出所有符合条件的团购
        List<BmsDxGroupBuy> returnBmsDxGroupBuys = new ArrayList<>();
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap));
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            speIds = bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getId).collect(Collectors.toSet());
            if(speIds.size() > 0) {
                //进行折扣去重
                if(isHaveDiscountDremoval) {
                    bmsDxGroupBuys = bmsDxGroupBuyDao.findAllMoreGroupBuyByRemoval(speIds);
                }
                List<Integer> algroIdsList = new LinkedList<>();
                if(bmsDxGroupBuys.size() > 0){
                    Set<Integer> conditionIds = bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getId).collect(Collectors.toSet());
                    if(conditionIds.size() > 0){
                        conditionMap.put("id_IN",conditionIds);
                        if(sortRule == null || sortRule == 0) {
                            sortRule = SORT_RULE_ONE;
                        }
                        if(sortRule == SORT_RULE_FOUR){
                            boolean noHaveLocation = false;
                            if((StringUtils.isNotBlank(addrCity) || StringUtils.isNotBlank(addrDistrict))
                                    && StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)){
                                bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap));
                                bmsDxGroupBuys = getAllLocationGroupBuy(bmsDxGroupBuys,addrCity,addrDistrict,latitude,longitude);
                                userDataMap.put("count",bmsDxGroupBuys.size());
                            }else{
                                noHaveLocation = true;
                            }
                            if(noHaveLocation){
                                postHandleBusiness(bmsDxGroupBuys);
                            }
                            postHandGroupBuySortDis(bmsDxGroupBuys);
                            if(bmsDxGroupBuys.size() > 0) {
                                bmsDxGroupBuys = costomPage(pageNum,pageSize,bmsDxGroupBuys);
                            }
                        }else {
                            if (sortRule == SORT_RULE_ONE) {
                                algroIdsList.addAll(getAlgorithmRecommendIds(paramsMap,latitude,longitude,addrDistrict));
                                /*List<Integer> groupIds = getAlgorithmRecommendIds(paramsMap,latitude,longitude,addrDistrict);
                                Set<Integer> algroIds = new HashSet<>();
                                if(groupIds.size() > 0){
                                    for(Integer groupId : groupIds){
                                        if(speIds.contains(groupId)){
                                            algroIds.add(groupId);
                                            algroIdsList.add(groupId);
                                        }
                                    }
                                }
                                if(algroIds.size() > 0){
                                    conditionMap.put("id_IN",algroIds);
                                }*/
                            } else if (sortRule == SORT_RULE_TWO) {
                                sort = Sort.by(Sort.Direction.ASC,"discountNum");
                            }else if(sortRule == SORT_RULE_THREE){
                                sort = Sort.by(Sort.Direction.DESC,"sellNum");
                            }else if(sortRule == SORT_RULE_FIVE){
                                sort = Sort.by(Sort.Direction.ASC,"groupPrice");
                            }else if(sortRule == SORT_RULE_SIX){
                                sort = Sort.by(Sort.Direction.DESC,"groupPrice");
                            }
                            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize,sort);
                            Page<BmsDxGroupBuy> bmsDxGroupBuyPage = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap),pageable);
                            bmsDxGroupBuys = bmsDxGroupBuyPage.getContent();
                            userDataMap.put("count",bmsDxGroupBuyPage.getTotalElements());
                            postHandleBusiness(bmsDxGroupBuys);
                            if(StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)){
                                postHandleGroupBuyDistince(bmsDxGroupBuys,latitude,longitude);
                            }
                        }
                    }
                }
                returnBmsDxGroupBuys = bmsDxGroupBuys;
                if(sortRule == SORT_RULE_ONE){
                    //将查出来的团购，以智能推荐的顺序进行推荐
                    if(returnBmsDxGroupBuys.size() > 0 && algroIdsList.size() > 0){
                        Map<Integer,BmsDxGroupBuy> bmsDxGroupBuyMap = new HashMap<>();
                        for(BmsDxGroupBuy bmsDxGroupBuy : returnBmsDxGroupBuys){
                            bmsDxGroupBuyMap.put(bmsDxGroupBuy.getId(),bmsDxGroupBuy);
                        }
                        List<BmsDxGroupBuy> sortBmsDxGroupBuy = new LinkedList<>();
                        for(Integer groupBuyId : algroIdsList){
                            if(bmsDxGroupBuyMap.containsKey(groupBuyId)){
                                sortBmsDxGroupBuy.add(bmsDxGroupBuyMap.get(groupBuyId));
                            }
                        }
                        returnBmsDxGroupBuys = sortBmsDxGroupBuy;
                    }
                }
            }
        }
        /*if(returnBmsDxGroupBuys.size() == Constants.COMMON_FLAG_FALSE_INT && isRecommend){
            //推荐一些销量高的团购
            conditionMap.clear();
            conditionMap.put("status",Constants.ONLINE_STATUS);
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"sellNum");
            Page<BmsDxGroupBuy> bmsDxGroupBuyPage = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap),pageable);
            returnBmsDxGroupBuys = bmsDxGroupBuyPage.getContent();
            userDataMap.put("count",bmsDxGroupBuyPage.getTotalElements());
            postHandleBusiness(returnBmsDxGroupBuys);
            if(StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)){
                postHandleGroupBuyDistince(bmsDxGroupBuys,latitude,longitude);
            }
        }*/
        postHandleBusinessHavingMoreGroupBuy(returnBmsDxGroupBuys);
        postHandleDiscount(returnBmsDxGroupBuys);
        userDataMap.put("serverTime",new Date());
        return ResultMapHelper.success(returnBmsDxGroupBuys,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String,Object> getAllGroupBuy_v2(ParamsMap paramsMap){
        CheckUserBo checkUserBo = RequestParamUtils.checkUserBo();
        GroupBuyConditionHolder groupBuyConditionHolder = new GroupBuyConditionHolder();
        //默认使用设备标识
        String userIdentify = null;
        if(checkUserBo.getCheckStatus().equals(ResultCode.CODE_NORMAL)){
            userIdentify = checkUserBo.getUserId();
        }
        String addrCity = paramsMap.getString("addrCity");
        String addrDistrict = paramsMap.getString("addrDistrict");
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Integer pageNum = paramsMap.getInteger("pageNum");
        Integer index = paramsMap.getInteger("index");

        //排序规则
        Integer sortRule = paramsMap.getInteger("sortRule");
        //智能排序
        final int SORT_RULE_ONE = 1;
        //折扣优先
        final int SORT_RULE_TWO = 2;
        //人气优先
        final int SORT_RULE_THREE = 3;
        //距离优先
        final int SORT_RULE_FOUR = 4;
        //低价优先
        final int SORT_RULE_FIVE = 5;
        //高价优先
        final int SORT_RULE_SIX = 6;
        //排序规则
        Sort sort = Sort.by(Sort.Direction.ASC,"id");
        //没有定位默认珠海市香洲区
        if(StringUtils.isBlank(addrCity) && StringUtils.isBlank(addrDistrict)){
            addrCity = "珠海市";
            addrDistrict = "香洲区";
        }
        Set<Integer> groupTypes = new HashSet<>(Arrays.asList(new Integer[]{BmsDxGroupBuyService.GROUP_TYPE_GEN
                , BmsDxGroupBuyService.GROUP_TYPE_TETE,BmsDxGroupBuyService.GROUP_TYPE_SECONDS_KILL,Constants.FX_ORDER_TYPE}));
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        int client = requestHeaderData.getClient();
        if(client == Constants.SMALL_PROGRAM) {
            groupTypes.add(BmsDxGroupBuyService.GROUP_TYPE_BARGAIN);
        }

        //团购id
        Set<Integer> groupBuyIds = new HashSet<>();
        //是否独家
        boolean isHave = false;
        Integer isExclusive = paramsMap.getInteger("isExclusive");
        if(isExclusive != null && isExclusive == Constants.COMMON_FLAG_TRUE_INT){
            isHave = true;
            groupBuyIds.addAll(this.getIsExclusiveGroupBuy());
        }
        //是否限时
        Integer isTimeLimit = paramsMap.getInteger("isTimeLimit");
        //是否低于5折
        if(isTimeLimit != null && isTimeLimit == Constants.COMMON_FLAG_TRUE_INT){
            //conditionMap.put("isTimeLimit",Constants.COMMON_FLAG_TRUE_INT);
            isHave = true;
            groupBuyIds.addAll(this.getIsTimeLimitGroupBuy());
        }
        Integer isLessthanFive = paramsMap.getInteger("isLessthanFive");
        if(isLessthanFive != null && isLessthanFive == Constants.COMMON_FLAG_TRUE_INT){
            final Double FIVE_DISCOUNT = 5d;
            //conditionMap.put("discount_LTT",FIVE_DISCOUNT);
            isHave = true;
            groupBuyIds.addAll(this.getLessDiscountGroupBuy(FIVE_DISCOUNT));
        }
        if(isHave){
            if(!(groupBuyIds.size() > 0)){
                groupBuyIds.add(Constants.NOT_IN);
            }
        }
        isHave = false;
        //todo 有标签搜索的情况
        Set<Integer> groupBuyIdsAnd = new HashSet<>();
        //有标签的情况
        if(paramsMap.containsKey("typeAndLabel")){
            isHave = true;
            JSONArray jsonArray = JSON.parseArray(paramsMap.getString("typeAndLabel"));
            for(int ii = 0;ii < jsonArray.size();ii++){
                Map<String,Object> typeLabel = jsonArray.getJSONObject(ii);
                Integer typeId = Integer.parseInt(typeLabel.get("typeId").toString());
                if(typeLabel.containsKey("labelIds")){
                    List<Integer> labelIds = (List<Integer>) typeLabel.get("labelIds");
                    if(labelIds.size() > 0){
                        groupBuyIdsAnd.addAll(this.getGroupBuyByLabelIds(groupTypes,labelIds));
                    }else {
                        groupBuyIdsAnd.addAll(this.getGroupBuyByTypeIds(groupTypes,typeId));
                    }
                }else {
                    groupBuyIdsAnd.addAll(this.getGroupBuyByTypeIds(groupTypes,typeId));
                }
            }
        }else {
            if (paramsMap.containsKey("labelIds")) {
                String labelArgs = paramsMap.getString("labelIds");
                if (StringUtils.isNotBlank(labelArgs)) {
                    List<Integer> labelIds = JSON.parseArray(labelArgs, Integer.class);
                    if (labelIds.size() > 0) {
                        groupBuyIdsAnd.addAll(this.getGroupBuyByLabelIds(groupTypes,labelIds));
                    }
                }
            }
        }
        if(isHave){
            if(groupBuyIdsAnd.size() == 0){
                groupBuyIdsAnd.add(Constants.NOT_IN);
            }
        }
        isHave = false;
        //todo 有商圈搜索的情况
        Set<Integer> groupCirclesIds = new HashSet<>();
        if(paramsMap.containsKey("businessCircles") && StringUtils.checkNullAndEmpty(paramsMap.get("businessCircles"))){
            isHave = true;
            String businessCircle = paramsMap.getString("businessCircles");
            Map<String,Object> circleCondition = (Map<String, Object>) JSON.parse(businessCircle);
            Set<Integer> businessIds = new HashSet<>();
            boolean isNotHaveCirId = true;
            //筛选出对应的地区的店铺
            String addrParentCity = circleCondition.get("addrParentCity").toString();
            String buinessCirCity = circleCondition.get("addCity").toString();
            boolean isHaveCirId = false;
            if(circleCondition.containsKey("cirId")){
                JSONArray jsonArray = (JSONArray) circleCondition.get("cirId");
                if(jsonArray.size() > 0) {
                    isHaveCirId = true;
                    List<String> businessCircleIds = (List<String>) JSON.parse(jsonArray.toJSONString());
                    Set<Integer> bcIds = new HashSet<>();
                    for(String b : businessCircleIds){
                        bcIds.add(Integer.parseInt(b));
                    }
                    groupCirclesIds.addAll(this.getGroupBuyByCirIds(groupTypes,bcIds));
                }
            }
            if(!isHaveCirId){
                if("热门商圈".equals(buinessCirCity)){
                    addrDistrict = "";
                    Set<Integer> areaIds = bmsBusinessAreaService.findHotByAddr(addrParentCity);
                    if(areaIds.size() > 0){
                        groupCirclesIds.addAll(this.getGroupBuyByCirIds(groupTypes,areaIds));
                    }
                }else {
                    addrCity = addrParentCity;
                    addrDistrict = buinessCirCity;
                    isHave = false;
                    groupBuyConditionHolder.setIsSearchAllCircles(Constants.COMMON_FLAG_TRUE_INT);
                }
            }
        }
        if(isHave){
            if(groupCirclesIds.size() == 0){
                groupCirclesIds.add(Constants.NOT_IN);
            }
        }
        //取交集
        groupBuyIdsAnd = WebUtils.getSpeSet(groupBuyIdsAnd,groupCirclesIds);
        isHave = false;
        //todo 有文本搜索的情况
        Set<Integer> groupBuySearchTextIds = new HashSet<>();
        String searchText = paramsMap.getStringSimple("searchText");
        if(StringUtils.isNotBlank(searchText)){
            bmsSearchService.recordHistorySearch_V2(userIdentify,searchText,Constants.GROUP_BUY_SEARCH);
            bmsSearchService.countHotSearch(searchText);
            isHave = true;
            groupBuySearchTextIds.addAll(this.findGroupBuyByGroupOrVendorName(searchText));
        }
        if(isHave){
            if(groupBuySearchTextIds.size() == 0){
                groupBuySearchTextIds.add(Constants.NOT_IN);
            }
        }
        groupBuyIdsAnd = WebUtils.getSpeSet(groupBuyIdsAnd,groupBuySearchTextIds);
        //取一个总的(上线的，符合类型的，符合地区)
        Set<Integer> groupBuyAllIds = new HashSet<>();
        if(groupBuyIdsAnd.size() == 0 && groupBuyIds.size() == 0){
            groupBuyAllIds = this.getAllGroupBuy(groupBuyConditionHolder,addrCity,addrDistrict,longitude,latitude,groupTypes);
        }else if(groupBuyIdsAnd.contains(Constants.NOT_IN) || groupBuyIds.contains(Constants.NOT_IN)){
            groupBuyAllIds.add(Constants.NOT_IN);
        }else{
            groupBuyAllIds = this.getAllGroupBuy(groupBuyConditionHolder,addrCity,addrDistrict,latitude,longitude,groupTypes);
            if(groupBuyAllIds.size() > 0 && groupBuyIdsAnd.size() > 0) {
                groupBuyAllIds = WebUtils.IntersectionBySet(groupBuyAllIds, groupBuyIdsAnd);
            }
            if(groupBuyAllIds.size() > 0 && groupBuyIds.size() > 0) {
                groupBuyAllIds = WebUtils.IntersectionBySet(groupBuyAllIds, groupBuyIds);
            }
        }

        //首页分类条件
        if(index != null){
            Set<Integer> indexIds = this.getGroupBuyByIndex(index);
            if(indexIds != null && indexIds.size() > 0 ){
                groupBuyAllIds = WebUtils.getSpeSet(groupBuyAllIds,indexIds);
            }else{
                groupBuyAllIds.clear();
            }
        }

        groupBuyIds = groupBuyAllIds;

        if(!(groupBuyIds.size() > 0)){
            groupBuyIds.add(Constants.NOT_IN);
        }
        //团购搜索条件
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("groupType_IN",groupTypes);
        conditionMap.put("id_IN",groupBuyIds);
        Map<String,Object> groupByMap = new HashMap<>();
        groupByMap.put("businessId_GB",Constants.COMMON_FLAG_TRUE_INT);
        //todo 排序条件
        if(sortRule == null || sortRule == 0) {
            sortRule = SORT_RULE_ONE;
        }
        List<Integer> algroIdsList = new LinkedList<>();
        Map<String,Object> userDataMap = new HashMap<>();
        List<BmsDxGroupBuy> bmsDxGroupBuys = new LinkedList<>();
        if(sortRule == SORT_RULE_FOUR){
            /*boolean noHaveLocation = false;
            if((StringUtils.isNotBlank(addrCity) || StringUtils.isNotBlank(addrDistrict))
                    && StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)){
                bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap,groupByMap));
                bmsDxGroupBuys = getAllLocationGroupBuy(bmsDxGroupBuys,addrCity,addrDistrict,latitude,longitude);
                userDataMap.put("count",bmsDxGroupBuys.size());
            }else{
                noHaveLocation = true;
            }
            if(noHaveLocation){
                postHandleBusiness(bmsDxGroupBuys);
            }
            postHandGroupBuySortDis(bmsDxGroupBuys);
            if(bmsDxGroupBuys.size() > 0) {
                bmsDxGroupBuys = costomPage(pageNum,pageSize,bmsDxGroupBuys);
            }*/
            bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap));
            if(StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
                Pageable pageable = BmsCommonService.getPageable(pageNum, pageSize);
                if (bmsDxGroupBuys.size() > 0) {
                    Set<Integer> resultIds = bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getId).collect(Collectors.toSet());
                    bmsDxGroupBuys = getNearGroupBuy(resultIds,longitude,latitude,pageable);
                    Integer groupBuyCount = bmsDxGroupBuyDao.countGroupBuyNum((Integer)conditionMap.get("status"),(Set)conditionMap.get("groupType_IN"),(Set)conditionMap.get("id_IN"));
                    userDataMap.put("count",groupBuyCount);
                    postHandleBusiness(bmsDxGroupBuys);
                    postHandleBusinessDistance(bmsDxGroupBuys, latitude, longitude);
                    postHandGroupBuySortDis(bmsDxGroupBuys);
                }
            }
        }else {
            if (sortRule == SORT_RULE_ONE) {
                sort = Sort.by(Sort.Direction.DESC,"newTime");
                //algroIdsList.addAll(getAlgorithmRecommendIds(paramsMap,latitude,longitude,addrDistrict));
                //log.info("智能排序推荐结果：" + algroIdsList.toString());
                //if(BmsCommonService.checkRunProfile(BmsCommonService.RUN_PRO)){
                    List<Integer> groupIds = new LinkedList<>();
//                    List<Integer> groupIds = getAlgorithmRecommendIds(paramsMap,latitude,longitude,addrDistrict);
                    log.info("智能排序推荐结果：" + groupIds);
                    Set<Integer> algroIds = new HashSet<>();
                    /*if(groupIds.size() > 0){
                        for(Integer groupId : groupIds){
                            if(groupBuyIds.contains(groupId)){
                                algroIds.add(groupId);
                                algroIdsList.add(groupId);
                            }
                        }
                    }*/
                    if(algroIds.size() > 0){
                        conditionMap.put("id_IN",algroIds);
                    }
                //}
            } else if (sortRule == SORT_RULE_TWO) {
                sort = Sort.by(Sort.Direction.ASC,"discountNum");
            }else if(sortRule == SORT_RULE_THREE){
                sort = Sort.by(Sort.Direction.DESC,"sellNum");
            }else if(sortRule == SORT_RULE_FIVE){
                sort = Sort.by(Sort.Direction.ASC,"groupPrice");
            }else if(sortRule == SORT_RULE_SIX){
                sort = Sort.by(Sort.Direction.DESC,"groupPrice");
            }
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize,sort);
            Page<BmsDxGroupBuy> bmsDxGroupBuyPage = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap,groupByMap),pageable);
            bmsDxGroupBuys = bmsDxGroupBuyPage.getContent();
            Integer groupBuyCount = bmsDxGroupBuyDao.countGroupBuyNum((Integer)conditionMap.get("status"),(Set)conditionMap.get("groupType_IN"),(Set)conditionMap.get("id_IN"));
            userDataMap.put("count",groupBuyCount);
            postHandleBusiness(bmsDxGroupBuys);
            if(StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)){
                postHandleGroupBuyDistince(bmsDxGroupBuys,latitude,longitude);
            }
            if(sortRule == SORT_RULE_ONE){
                //将查出来的团购，以智能推荐的顺序进行推荐
                if(bmsDxGroupBuys.size() > 0 && algroIdsList.size() > 0){
                    Map<Integer,BmsDxGroupBuy> bmsDxGroupBuyMap = new HashMap<>();
                    for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                        bmsDxGroupBuyMap.put(bmsDxGroupBuy.getId(),bmsDxGroupBuy);
                    }
                    List<BmsDxGroupBuy> sortBmsDxGroupBuy = new LinkedList<>();
                    for(Integer groupBuyId : algroIdsList){
                        if(bmsDxGroupBuyMap.containsKey(groupBuyId)){
                            sortBmsDxGroupBuy.add(bmsDxGroupBuyMap.get(groupBuyId));
                        }
                    }
                    if(sortBmsDxGroupBuy.size() >= pageSize){
                        bmsDxGroupBuys = sortBmsDxGroupBuy;
                    }
                }
            }
        }
        bmsDxGroupBuys = postHandleBusinessHavingMoreGroupBuy_v2(bmsDxGroupBuys,searchText);
        postHandleDiscount(bmsDxGroupBuys);
        userDataMap.put("serverTime",new Date());
        List<GetAllGroupBuy_v2Vo> getAllGroupBuy_v2Vos = postHandleCleanData(bmsDxGroupBuys);


        //处理图片字段
        imgPrefixService.pushSpliceField(getAllGroupBuy_v2Vos,"groupImg","cloudCoverUrl");
        getAllGroupBuy_v2Vos.forEach(v->{
            imgPrefixService.pushSpliceField(v.getBmsBusiness(),"logoUrl");
            if(v.getBmsBusiness() != null){
                imgPrefixService.pushSpliceField(v.getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");

            }});
        return ResultMapHelper.success(getAllGroupBuy_v2Vos,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    private void postHandleBusinessDistance(List<BmsDxGroupBuy> bmsDxGroupBuys,String latitude,String longitude) {
        if(CollectionUtils.isNotEmpty(bmsDxGroupBuys)){
            List<BusinessRpDto> businessRpDtos = bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getBmsBusiness).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(businessRpDtos)){
                for (BusinessRpDto business : businessRpDtos) {
                    if (StringUtils.isNotBlank(business.getLatitude()) && StringUtils.isNotBlank(business.getLongitude())) {
                        double lat = Double.parseDouble(business.getLatitude());
                        double lnt = Double.parseDouble(business.getLongitude());
                        double distance = LocationUtils.getDistance(lat, lnt, Double.parseDouble(latitude), Double.parseDouble(longitude));
                        distance = ArithUtil.round(distance,2);
                        business.setDistance(distance);
                    }
                }
            }
        }
    }

    private List<BmsDxGroupBuy> getNearGroupBuy(Set<Integer> resultIds,String longitude,String latitude,Pageable pageable) {
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.getNearGroupBuy(resultIds,longitude,latitude,pageable);
        return bmsDxGroupBuys;
    }

    public List<GetAllGroupBuy_v2Vo> postHandleCleanData(List<BmsDxGroupBuy> bmsDxGroupBuys){
        List<GetAllGroupBuy_v2Vo> getAllGroupBuy_v2Vos = new LinkedList<>();
        if(CollectionUtils.isNotEmpty(bmsDxGroupBuys)){
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys) {
                GetAllGroupBuy_v2Vo getAllGroupBuy_v2Vo = BeanUtils.copyProperties(bmsDxGroupBuy, GetAllGroupBuy_v2Vo.class);
                GetAllGroupBuy_v2Vo.BmsBusinessVo bmsBusinessVo = BeanUtils.copyProperties(bmsDxGroupBuy.getBmsBusiness(),GetAllGroupBuy_v2Vo.BmsBusinessVo.class);
                bmsBusinessVo.setOtherGroupBuys(BeanUtils.copyList(bmsDxGroupBuy.getBmsBusiness().getOtherGroupBuys(),GetAllGroupBuy_v2Vo.OtherGroupBuy.class));
                if(bmsBusinessVo.getOtherGroupBuys().size() > 0){
                    //兼容小程序
                }
                if(bmsBusinessVo != null) {
                    getAllGroupBuy_v2Vo.setBmsBusiness(bmsBusinessVo);
                    getAllGroupBuy_v2Vo.setBusinessName(bmsBusinessVo.getVendorName());
                }
                getAllGroupBuy_v2Vos.add(getAllGroupBuy_v2Vo);
            }
        }
        return getAllGroupBuy_v2Vos;
    }

    private Set<Integer> getAllGroupBuy(GroupBuyConditionHolder groupBuyConditionHolder,String addrCity, String addrDistrict,String longitude,String latitude,Set<Integer> groupTypes) {
        Set<Integer> groupBuyIds = new HashSet<>();
        groupBuyIds.addAll(bmsDxGroupBuyDao.getAllGroupBuy(addrCity,addrDistrict,groupTypes));
        if(StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude) && groupBuyConditionHolder.getIsSearchAllCircles()
                == Constants.COMMON_FLAG_FALSE_INT){
            if(groupBuyIds.size() > 0){
                groupBuyIds.addAll(bmsDxGroupBuyDao.getGroupBuyByLatitudeLongitude(longitude,latitude,groupTypes,groupBuyIds));
            }
            groupBuyIds.addAll(bmsDxGroupBuyDao.getGroupBuyByLatitudeLongitude(longitude,latitude,groupTypes));
        }
        return groupBuyIds;
    }

    private Set<Integer> getGroupBuyByCirIds(Set<Integer> groupTypes, Set<Integer> bcIds) {
        return bmsDxGroupBuyDao.getGroupBuyByCirIds(groupTypes,bcIds);
    }

    private Set<Integer> getGroupBuyByTypeIds(Set<Integer> groupTypes, Integer typeId) {
        return bmsDxGroupBuyDao.getGroupBuyByTypeIds(groupTypes,typeId);
    }

    private Set<Integer> getGroupBuyByLabelIds(Set<Integer> groupTypes,List<Integer> labelIds) {
        return bmsDxGroupBuyDao.getGroupBuyByLabelIds(groupTypes,labelIds);
    }

    public Set<Integer> getIsExclusiveGroupBuy(){
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findByStatusAndIsExclusive(Constants.ONLINE_STATUS,Constants.COMMON_FLAG_TRUE_INT);
        return bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getId).collect(Collectors.toSet());
    }

    public Set<Integer> getIsTimeLimitGroupBuy(){
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findByStatusAndIsTimeLimit(Constants.ONLINE_STATUS,Constants.COMMON_FLAG_TRUE_INT);
        return bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getId).collect(Collectors.toSet());
    }

    public Set<Integer> getIsBargainGroupBuy(){
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findByStatusAndGroupType(Constants.ONLINE_STATUS,BmsDxGroupBuyService.GROUP_TYPE_BARGAIN);
        return bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getId).collect(Collectors.toSet());
    }

    public Set<Integer> getLessDiscountGroupBuy(Double discountNum){
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findByStatusAndDiscountNumLessThan(Constants.ONLINE_STATUS,discountNum);
        return bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getId).collect(Collectors.toSet());
    }

    private List<Integer> getAlgorithmRecommendIds(ParamsMap paramsMap, String latitude, String longitude,String addr) {
        List<Integer> groupBuyIds = new LinkedList<>();
        try {
            if(StringUtils.isBlank(latitude)){
                latitude = "";
            }
            if(StringUtils.isBlank(longitude)){
                longitude = "";
            }
            if(StringUtils.isBlank(addr)){
                addr = "";
            }
            RequestHeaderData requestHeaderData = new RequestHeaderData();
            String userId = requestHeaderData.getString("devid");
            if(paramsMap.containsKey("userIdentify") && StringUtils.checkNullAndEmpty(paramsMap.getString("userIdentify"))){
                userId = paramsMap.getString("userIdentify");
            }
            String recommendUrl = AppConfig.getProperty("syniGroupBuyRecAddress") + "/groupBuySort";
            Map<String,Object> params = new HashMap<>();
            params.put("uid",userId);
            params.put("latitude",latitude);
            params.put("longitude",longitude);
            params.put("addr",addr);
            log.info("传参数据： " + JSON.toJSONString(params));
            String reponseBody = RestTemplateUtils.postForEntityForJson(recommendUrl,params);
            BmsCommonService.getLogger(this.getClass()).info(reponseBody);
            if(StringUtils.isNotBlank(reponseBody)){
                JSONObject jsonObject = JSON.parseObject(reponseBody);
                if(jsonObject.containsKey("status") && ResultCode.CODE_NORMAL.equals(jsonObject.getString("status"))){
                    //去redis里面找
                    String userGroupBuyRedisKey = Constants.REDIS_KEY_GROUPBUY_RECOMMEND + userId;
                    long size = redisTemplate.opsForList().size(userGroupBuyRedisKey);
                    List<Integer> gIds = redisTemplate.opsForList().range(userGroupBuyRedisKey,0,size);
                    groupBuyIds.addAll(gIds);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return groupBuyIds;
    }

    private Set<Integer> findGroupNameGroupBuyIds(String searchText) {
        Set<Integer> groupIds = new HashSet<>();
        List<Map<String,Object>> resultMap = bmsDxGroupBuyDao.getGroupBuyIdsByGroupName(searchText);
        if(resultMap != null && resultMap.size() > 0){
            for(Map<String,Object> obj : resultMap){
                groupIds.add(Integer.parseInt(obj.get("id").toString()));
            }
        }
        return groupIds;
    }

    public Set<Integer> findVendorNameGroupBuyIds(String searchText) {
        Set<Integer> businessIds = new HashSet<>();
        List<Map<String,Object>> resultMap = bmsDxGroupBuyDao.getGroupBuyIdsByVendorName(searchText);
        if(resultMap != null && resultMap.size() > 0){
            for(Map<String,Object> obj : resultMap){
                businessIds.add(Integer.parseInt(obj.get("id").toString()));
            }
        }
        return businessIds;
    }

    public Set<Integer> getGroupBuyIdsByVendorNameDistinct(String searchText) {
        Set<Integer> businessIds = new HashSet<>();
        List<Map<String,Object>> resultMap = bmsDxGroupBuyDao.getGroupBuyIdsByVendorNameAndDistinct(searchText);
        if(resultMap != null && resultMap.size() > 0){
            for(Map<String,Object> obj : resultMap){
                businessIds.add(Integer.parseInt(obj.get("id").toString()));
            }
        }
        return businessIds;
    }

    public Set<Integer> findGroupBuyByVendorName(String searchText) {
        Set<Integer> businessIds = new HashSet<>();
        List<Map<String,Object>> resultMap = bmsDxGroupBuyDao.getGroupBuyIdByVendorName(searchText);
        if(resultMap != null && resultMap.size() > 0){
            for(Map<String,Object> obj : resultMap){
                businessIds.add(Integer.parseInt(obj.get("id").toString()));
            }
        }
        return businessIds;
    }


    private Set<Integer> findGroupBuyName(String searchText, Set<Integer> speIds) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("status",Constants.ONLINE_STATUS);
        conditionMap.put("groupName_LIKE",searchText);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        if(speIds.size() > 0) {
            conditionMap.put("id_IN",speIds);
        }
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap));
        speIds.clear();
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            speIds.addAll(bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getId).collect(Collectors.toSet()));
        }else {
            speIds.add(Constants.NOT_IN);
        }
        return speIds;
    }

    private Set<Integer> findSpecialGroupBuy(Integer isExclusive, Integer isTimeLimit) {
        List<Map<String,Object>> resultMap = new ArrayList<>();
        if(isExclusive != null && isExclusive == Constants.COMMON_FLAG_TRUE_INT) {
            resultMap.addAll(bmsDxGroupBuyDao.findSpecialGroupBuyByEx());
        }
        if(isTimeLimit != null && isTimeLimit == Constants.COMMON_FLAG_TRUE_INT) {
            resultMap.addAll(bmsDxGroupBuyDao.findSpecialGroupBuyByTimeLimit());
        }
        Set<Integer> groupBuyIds = new HashSet<>();
        if(resultMap != null && resultMap.size() > 0){
            for(Map<String,Object> obj : resultMap){
                Integer groupBuyId = Integer.parseInt(obj.get("id").toString());
                groupBuyIds.add(groupBuyId);
            }
        }else {
            if(!(isExclusive == null && isTimeLimit == null)){
                groupBuyIds.add(0);
            }
        }
        return groupBuyIds;
    }

    private void postHandleBusinessHavingMoreGroupBuy(List<BmsDxGroupBuy> bmsDxGroupBuys) {
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            Set<Integer> businessIds = new HashSet<>();
            Set<Integer> groupBuyIds = new HashSet<>();
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                if(bmsDxGroupBuy.getBmsBusiness() != null){
                    businessIds.add(bmsDxGroupBuy.getBusinessId());
                }
                groupBuyIds.add(bmsDxGroupBuy.getId());
            }
            Map<Integer,List<BmsDxGroupBuy>> groupBuyMap = findBusinessHavingMoreGroupBuy(businessIds,groupBuyIds);
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                if(bmsDxGroupBuy.getBmsBusiness() != null){
                    if(groupBuyMap.containsKey(bmsDxGroupBuy.getBusinessId())){
                        bmsDxGroupBuy.getBmsBusiness().setIsHavingMoreGroupBuy(Constants.COMMON_FLAG_TRUE_INT);
                        bmsDxGroupBuy.getBmsBusiness().setOtherGroupBuys(groupBuyMap.get(bmsDxGroupBuy.getBusinessId()));
                    }
                }
            }
        }
    }

    private List<BmsDxGroupBuy> postHandleBusinessHavingMoreGroupBuy_v2(List<BmsDxGroupBuy> bmsDxGroupBuys,String searchText) {
        List<BmsDxGroupBuy> buys = new LinkedList<>();
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            Set<Integer> businessIds = new HashSet<>();
            Set<Integer> groupBuyIds = new HashSet<>();
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                if(bmsDxGroupBuy.getBmsBusiness() != null){
                    businessIds.add(bmsDxGroupBuy.getBusinessId());
                }
                groupBuyIds.add(bmsDxGroupBuy.getId());
            }
            Map<Integer,List<BmsDxGroupBuy>> groupBuyMap = findBusinessHavingMoreGroupBuy(businessIds,groupBuyIds);
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                if(bmsDxGroupBuy.getBmsBusiness() != null){
                    if(groupBuyMap.containsKey(bmsDxGroupBuy.getBusinessId())){
                        List<BmsDxGroupBuy> otherBuys = groupBuyMap.get(bmsDxGroupBuy.getBusinessId());
                        postHandleDiscount(otherBuys);
                        bmsDxGroupBuy.getBmsBusiness().setOtherGroupBuys(otherBuys);
                        bmsDxGroupBuy.getBmsBusiness().setIsHavingMoreGroupBuy(Constants.COMMON_FLAG_TRUE_INT);
                        //对比当前groupBuy的折扣
                       /* if(otherBuys.size() > 0) {
                            BmsDxGroupBuy minDisCountGroupBuy = bmsDxGroupBuy;
                            List<BmsDxGroupBuy> otherCountMax = new LinkedList<>();
                                for (BmsDxGroupBuy b : otherBuys){
                                    if(b.getDiscountNum() < minDisCountGroupBuy.getDiscountNum()
                                            && !(StringUtils.isNotBlank(searchText) && (bmsDxGroupBuy.getBmsBusiness().getVendorName().indexOf(searchText) != -1
                                            || bmsDxGroupBuy.getGroupName().indexOf(searchText) != -1) )){
                                        BusinessRpDto businessRpDto = minDisCountGroupBuy.getBmsBusiness();
                                        minDisCountGroupBuy.setBmsBusiness(null);
                                        otherCountMax.add(minDisCountGroupBuy);
                                        b.setBmsBusiness(businessRpDto);
                                        minDisCountGroupBuy = b;
                                        //bmsDxGroupBuy = minDisCountGroupBuy;
                                    }else {
                                        otherCountMax.add(b);
                                    }
                                }
                                bmsDxGroupBuy = minDisCountGroupBuy;

                            bmsDxGroupBuy.getBmsBusiness().setIsHavingMoreGroupBuy(Constants.COMMON_FLAG_TRUE_INT);
                            bmsDxGroupBuy.getBmsBusiness().setOtherGroupBuys(otherCountMax);
                        }*/
                    }
                    buys.add(bmsDxGroupBuy);
                }
            }
        }
        return buys;
    }

    private Map<Integer, List<BmsDxGroupBuy>> findBusinessHavingMoreGroupBuy(Set<Integer> businessIds, Set<Integer> groupBuyIds) {
        RequestHeaderData requestHeaderData = new RequestHeaderData();
//        //每个店铺最多10条
//        final int MAX_LIMIT = 10;
        Map<Integer,List<BmsDxGroupBuy>> resultMap = new HashMap<>();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("businessId_IN",businessIds);
        conditionMap.put("id_NIN",groupBuyIds);
        Set<Integer> groupType = new HashSet<>(Arrays.asList(new Integer[]{
                Constants.GROUP_TYPE_GEN,Constants.GROUP_TYPE_TETE,Constants.GROUP_TYPE_MS}));
        int client = requestHeaderData.getInteger("client");
        if(client == Constants.SMALL_PROGRAM) {
            groupType.add(Constants.GROUP_TYPE_BARGAIN);
        }
        conditionMap.put("groupType_IN",groupType);
        List<BmsDxGroupBuy> bmsDxGroupBuys =  bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap));
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys){
                if(!resultMap.containsKey(bmsDxGroupBuy.getBusinessId())){
                    resultMap.put(bmsDxGroupBuy.getBusinessId(),new ArrayList<>());
                }
//                if(resultMap.get(bmsDxGroupBuy.getBusinessId()).size() < MAX_LIMIT){
                    resultMap.get(bmsDxGroupBuy.getBusinessId()).add(bmsDxGroupBuy);
//                }
            }
        }
        return resultMap;
    }

    private Map<Integer, Integer> checkBusinessHavingMoreGroupBuy(Set<Integer> businessIds) {
        Map<Integer,Integer> resultMap = new HashMap<>();
        List<Map<String,Object>> results =  bmsDxGroupBuyDao.countBusinessMoreGroupBuy(businessIds);
        if(results != null && results.size() > 0){
            for(Map<String,Object> res : results){
                Integer businessId = Integer.parseInt(res.get("businessId").toString());
                resultMap.put(businessId,Constants.COMMON_FLAG_TRUE_INT);
            }
        }
        return resultMap;


    }

    public List<BmsDxGroupBuy> costomPage(Integer pageNum, Integer pageSize, List<BmsDxGroupBuy> bmsDxGroupBuys){
        Integer startIndex = (pageNum - 1) * pageSize;
        Integer endIndex = startIndex + pageSize;
        if(bmsDxGroupBuys.size() > startIndex) {
            if (endIndex > bmsDxGroupBuys.size()) {
                endIndex = bmsDxGroupBuys.size();
            }
            bmsDxGroupBuys = bmsDxGroupBuys.subList(startIndex, endIndex);
        }else {
            bmsDxGroupBuys = new LinkedList<>();
        }
        return bmsDxGroupBuys;
    }

    private void hanleNoData(List<BmsDxGroupBuy> resultList,Set businessIds,int end) {
        //乱序
        final int MAX_GET = 10;
        //计算当前页数
        Integer pageNum = (end - 3) / 3 + 1;
        Pageable pageable = BmsCommonService.getPageable(pageNum,MAX_GET, Sort.Direction.DESC,"sell_num");
        List<BmsDxGroupBuy> buys = bmsDxGroupBuyDao.findOrdinaryMoreGroupBuy(businessIds,pageable);
        if(buys != null && buys.size() > 0){
            for(BmsDxGroupBuy bmsDxGroupBuy : buys){
                resultList.add(bmsDxGroupBuy);
            }
        }
        postHandleBusiness(resultList);
    }

    private List<BmsDxGroupBuy> postHandGroupBuySort(List<BmsDxGroupBuy> resultList) {
        LinkedList<BmsDxGroupBuy> bmsDxGroupBuys = new LinkedList<>();
        for(int ii = 0;ii < resultList.size();ii++){
            int random = (int)(Math.random() * resultList.size());
            bmsDxGroupBuys.add(resultList.get(random));
            resultList.remove(random);
        }
        return bmsDxGroupBuys;
    }

    private void postHandGroupBuySortDis(List<BmsDxGroupBuy> resultList) {
        if(resultList.size() > 0){
            Collections.sort(resultList, new Comparator<BmsDxGroupBuy>() {
                @Override
                public int compare(BmsDxGroupBuy o1, BmsDxGroupBuy o2) {
                    if(o1.getBmsBusiness().getDistance() < o2.getBmsBusiness().getDistance()) {
                        return -1;
                    }else if(o1.getBmsBusiness().getDistance() == o2.getBmsBusiness().getDistance()){
                        return 0;
                    }
                    return 1;
                }
            });
        }
    }

    public void postHandleDiscount(List<BmsDxGroupBuy> resultGroupBuyList) {
        if(resultGroupBuyList != null && resultGroupBuyList.size() > 0){
            for(BmsDxGroupBuy bmsDxGroupBuy : resultGroupBuyList){
                postHandleDiscount(bmsDxGroupBuy);
            }
            bmsDxGroupBuyDao.saveAll(resultGroupBuyList);
        }
    }

    public void postHandleDiscount(BmsDxGroupBuy bmsDxGroupBuy) {
        if(bmsDxGroupBuy.getGroupPrice() != null && bmsDxGroupBuy.getGroupValue() != null) {
            if(bmsDxGroupBuy.getDiscountNum() == null) {
                Double discount = ArithUtil.div(bmsDxGroupBuy.getGroupPrice(), bmsDxGroupBuy.getGroupValue(), 2);
                Double disDesc = ArithUtil.round(ArithUtil.mul(discount, 10), 1);
                bmsDxGroupBuy.setDiscountNum(disDesc);
                bmsDxGroupBuy.setDiscount(String.format("%s折", String.valueOf(disDesc)));
            }
        }
    }

    public Set<Integer> getStartPayUidBusiness(){
        Set<Integer> businessIds = new HashSet<>();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("alipayStatus",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("alipayUser_NN",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("alipayUid_NN",Constants.COMMON_FLAG_TRUE_INT);
        List<BmsBusinessInfo> bmsBusinessInfos = bmsBusinessinfoService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        if(bmsBusinessInfos != null && bmsBusinessInfos.size() > 0){
            for(BmsBusinessInfo bmsBusinessInfo : bmsBusinessInfos){
                businessIds.add(bmsBusinessInfo.getBusinessId());
            }
        }
        return businessIds;
    }

    @Override
    public Map<String,Object> postLimitBuyLogic(Integer groupBuyId) {
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyDao.findByIdAndIsDelete(groupBuyId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupBuy == null) {
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,"团购不存在");
        }
        if(bmsDxGroupBuy.getIsTimeLimit() != null && bmsDxGroupBuy.getIsTimeLimit() == Constants.COMMON_FLAG_TRUE_INT){
            doGroupBuyTiming(LimitGroupBuyTimingJob.class,bmsDxGroupBuy);
            return ResultMapHelper.success();
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,"参数不对");
    }

    /**
     * @Description 定时取消订单
     * @Author: cfx
     * @Date: 2019/8/14
     */
    public void doGroupBuyTiming(Class classes,BmsDxGroupBuy bmsDxGroupBuy){
        //延长5分钟
        //startDate = DateTimeUtils.addMinutes(startDate,Constants.AUTO_CANCEL_ORDER_MINUTE_EXTEND);
        //设置开始任务
        if(bmsDxGroupBuy.getStartSellTime() != null) {
            String jobName = Constants.GEN_JOB_NAME + "limitGroupBuy_startSell" + bmsDxGroupBuy.getId();
            String triggerName = Constants.GEN_TRI_NAME + "limitGroupBuy_startSell" + bmsDxGroupBuy.getId();
            Map<String,Object> jsonDataMap = new HashMap<>();
            jsonDataMap.put("bmsDxGroupBuy",bmsDxGroupBuy);
            jsonDataMap.put("handle",LimitGroupBuyTimingJob.HANDLE_ONE);
            QuartzDo.setTask(classes,jobName,triggerName,bmsDxGroupBuy.getStartSellTime(),jsonDataMap);
        }
        //结束任务
        if(bmsDxGroupBuy.getLimitBuyTime() != null) {
            String jobName = Constants.GEN_JOB_NAME + "limitGroupBuy_endSell" + bmsDxGroupBuy.getId();
            String triggerName = Constants.GEN_TRI_NAME + "limitGroupBuy_endSell" + bmsDxGroupBuy.getId();
            Map<String,Object> jsonDataMap = new HashMap<>();
            jsonDataMap.put("bmsDxGroupBuy",bmsDxGroupBuy);
            jsonDataMap.put("handle",LimitGroupBuyTimingJob.HANDLE_TWO);
            QuartzDo.setTask(classes,jobName,triggerName,bmsDxGroupBuy.getLimitBuyTime(),jsonDataMap);
        }
    }

    @Override
    public Set<Integer> findGroupBuyByGroupName(String searchText) {
        Set<Integer> groupIds = new HashSet<>();
        //Set<Integer> businessIds = bmsBusinessService.findOnlineBusinessIds();
        //if(businessIds.size() > 0){
            Map<String,Object> conditionMap = new HashMap<>();
            conditionMap.put("status",Constants.ONLINE_STATUS);
            conditionMap.put("groupName_LIKE",searchText);
            conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
            //conditionMap.put("businessId_IN",businessIds);
            List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap));
            if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
                groupIds.addAll(bmsDxGroupBuys.stream().map(BmsDxGroupBuy::getId).collect(Collectors.toSet()));
            }
        //}
        return groupIds;
    }

    @Override
    public Set<Integer> findGroupBuyByGroupOrVendorName(String searchText) {
        Set<Integer> groupBuyIds = new HashSet<>();
        List<Map<String,Object>> resultMap =  bmsDxGroupBuyDao.getGroupBuyByGroupOrVendorName(searchText);;
        if(resultMap != null && resultMap.size() > 0){
            for(Map<String,Object> obj : resultMap){
                groupBuyIds.add(Integer.parseInt(obj.get("id").toString()));
            }
        }
        return groupBuyIds;
    }

    @Override
    @Transactional
    public void uploadBmsDxGroupBuy(Set<Integer> businessIds) {
        Date nowTime = new Date();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("businessId_IN",businessIds);
        conditionMap.put("status",Constants.ONLINE_STATUS);
        List<BmsDxGroupBuy> bmsDxGroupBuys = bmsDxGroupBuyDao.findAll(new SpecificationUtils(conditionMap));
        if(bmsDxGroupBuys != null && bmsDxGroupBuys.size() > 0){
            for(BmsDxGroupBuy bmsDxGroupBuy : bmsDxGroupBuys) {
                //下线
                bmsDxGroupBuy.setStatus(Constants.ROLLED_ONLINE_STATUS);
                bmsDxGroupBuy.setOfflineTime(nowTime);
                bmsDxGroupBuyRecordService.addGroupBuyRecord(bmsDxGroupBuy, BmsDxGroupBuyRecordService.RECORD_OFFLINE);
                //同时新建一个全新的到已下线的团购券
                /*BmsDxGroupBuy newBmsGroupBuy = new BmsDxGroupBuy();
                BeanUtils.copyProperties(bmsDxGroupBuy, newBmsGroupBuy);
                newBmsGroupBuy.setStatus(Constants.ROLLED_ONLINE_STATUS);
                newBmsGroupBuy.setId(null);
                newBmsGroupBuy.setSellNum(Constants.COMMON_FLAG_FALSE_INT);
                newBmsGroupBuy.setFinishNum(Constants.COMMON_FLAG_FALSE_INT);
                newBmsGroupBuy.setViewsNum(Constants.COMMON_FLAG_FALSE_INT);
                bmsDxGroupBuyDao.save(newBmsGroupBuy);*/
                bmsDxGroupBuyDao.save(bmsDxGroupBuy);
            }
        }
    }

    @Override
    public Map<Integer, Integer> countGroupBuyNumByBusinessIds(Set businessIds) {
        Map<Integer,Integer> groupBuyNumMap = new HashMap<>();
        Set<Integer> groupTypes = new HashSet<>();
        groupTypes.add(Constants.GROUP_TYPE_GEN);
        groupTypes.add(Constants.GROUP_TYPE_TETE);
        Set<Integer> statuses = new HashSet<>();
        statuses.add(Constants.ONLINE_STATUS);
        List<Map<String,Object>> countMap = bmsDxGroupBuyDao.countBusinessGroupBuyNum(businessIds,groupTypes,statuses);
        if(CollectionUtils.isNotEmpty(countMap)){
            countMap.forEach(obj -> {
                groupBuyNumMap.put(Integer.parseInt(obj.get("businessId").toString()),Integer.parseInt(obj.get("num").toString()));
            });
        }
        return groupBuyNumMap;
    }

    @Override
    public Set<Integer> getGroupBuyByIndex(Integer index) {
        String goldConfig = bmsDxConfigService.getConfigByCode(BmsDxConfigService.MDD_GOLD_CODE);
        if(StringUtils.isNotBlank(goldConfig)) {
            List<GoldRpDto> goldListMap = (List<GoldRpDto>)JSON.parseArray(goldConfig,GoldRpDto.class);
            if(goldListMap.size()>0){
                GoldRpDto goldRpDto = goldListMap.stream().filter((e)->e.getIndex()==index).collect(Collectors.toList()).get(0);
                if(goldRpDto != null){
                    JSONArray ids =   goldRpDto.getGroupIds();
                    List<Integer> idArr = JSONObject.parseArray(ids.toJSONString(),Integer.class);
                    if(idArr.size()>0){
                        return new HashSet<>(idArr);
                    }
                }
            }

        }
        return null;
    }

    @Override
    public void postHandleShowTemplateId(BmsDxGroupBuy bmsDxGroupBuy) {
        //美食模板（形成映射）
        if(bmsDxGroupBuy != null && bmsDxGroupBuy.getGroupTemplateId() != null){
            if(FRONT_TEMPATE_MAP.containsKey(bmsDxGroupBuy.getGroupTemplateId())){
                bmsDxGroupBuy.setShowTemplateId(FRONT_TEMPATE_MAP.get(bmsDxGroupBuy.getGroupTemplateId()));
            }
        }
    }

    @Override
    public void postHandleGroupDetailImg(BmsDxGroupBuy bmsDxGroupBuy) {
        try {
            if(StringUtils.isNotBlank(bmsDxGroupBuy.getGroupDetails())){
                bmsDxGroupBuy.setGroupDetailArray(JSONObject.parseArray(bmsDxGroupBuy.getGroupDetails(),String.class));
            }
            if(CollectionUtils.isEmpty(bmsDxGroupBuy.getGroupDetailArray())){
                if(StringUtils.isNotBlank(bmsDxGroupBuy.getDetailImg())){
                    bmsDxGroupBuy.getGroupDetailArray().add(bmsDxGroupBuy.getDetailImg());
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    @Override
    public Map<String, Object> getMerchantGroupBuyDetail(ParamsMap paramsMap) {
        Integer groupBuyId = paramsMap.getInteger("groupBuyId");
        Optional<BmsDxGroupBuy> bmsDxGroupBuyOptional = bmsDxGroupBuyDao.findById(groupBuyId);
        if(!bmsDxGroupBuyOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_05,ResultMsg.CODE_ERROR_05);
        }
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyOptional.get();
        //BmsBusiness bmsBusiness = bmsBusinessService.getBusinessById(bmsDxGroupBuy.getBusinessId());
        GetMerchantGroupBuyDetailRpVo rpVo = new GetMerchantGroupBuyDetailRpVo();
        //组装数据
        if(bmsDxGroupBuy != null){
            bmsDxGroupBuyService.postHandleGroupContent(bmsDxGroupBuy);
            bmsDxGroupBuyService.postHandleBusiness(bmsDxGroupBuy);
            bmsDxGroupBuyService.postHandleShowTemplateId(bmsDxGroupBuy);
            postHandleDraftBoxGroupBuy(bmsDxGroupBuy);
            SearchCouponDetailDto.BmsGroupBuyDetailData bmsGroupBuyDetailData = BeanUtils.copyProperties(bmsDxGroupBuy, SearchCouponDetailDto.BmsGroupBuyDetailData.class);
            try {
                if(StringUtils.isNotBlank(bmsDxGroupBuy.getGroupPhotosSmall())){
                    bmsGroupBuyDetailData.setGroupPhotos(JSONObject.parseArray(bmsDxGroupBuy.getGroupPhotosSmall(),String.class));
                }
                if(CollectionUtils.isEmpty(bmsGroupBuyDetailData.getGroupPhotos())){
                    if(StringUtils.isNotBlank(bmsDxGroupBuy.getGroupPhotos())){
                        bmsGroupBuyDetailData.setGroupPhotos(JSONObject.parseArray(bmsDxGroupBuy.getGroupPhotos(),String.class));
                    }
                }
                if(CollectionUtils.isEmpty(bmsGroupBuyDetailData.getGroupPhotos())){
                    if(StringUtils.isNotBlank(bmsDxGroupBuy.getGroupImg())){
                        bmsGroupBuyDetailData.getGroupPhotos().add(bmsDxGroupBuy.getGroupImg());
                    }
                }
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
            try {
                if(StringUtils.isNotBlank(bmsDxGroupBuy.getGroupDetails())){
                    bmsGroupBuyDetailData.setGroupDetails(JSONObject.parseArray(bmsDxGroupBuy.getGroupDetails(),String.class));
                }
                if(CollectionUtils.isEmpty(bmsGroupBuyDetailData.getGroupDetails())){
                    if(StringUtils.isNotBlank(bmsDxGroupBuy.getDetailImg())){
                        bmsGroupBuyDetailData.getGroupDetails().add(bmsDxGroupBuy.getDetailImg());
                    }
                }
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
            if(bmsDxGroupBuy.getBmsBusiness() != null) {
                SearchCouponDetailDto.BusinessData businessData = new SearchCouponDetailDto.BusinessData();
                businessData.setVendorName(bmsDxGroupBuy.getBmsBusiness().getVendorName());
                businessData.setLogoUrl(bmsDxGroupBuy.getBmsBusiness().getLogoUrl());
                bmsGroupBuyDetailData.setBusinessData(businessData);
            }
            if(StringUtils.isNotBlank(bmsDxGroupBuy.getGroupContent())) {
                List<SearchCouponDetailDto.GroupContent> groupContent = BeanUtils.copyList(bmsDxGroupBuy.getGroupContentRpDto(), SearchCouponDetailDto.GroupContent.class);
                bmsGroupBuyDetailData.setGroupContent(groupContent);
            }
            rpVo.setGroupBuyDetailData(bmsGroupBuyDetailData);
            rpVo.setOldGroupBuyDetailData(bmsDxGroupBuy);
        }
        return ResultMapHelper.success(rpVo,ResultMsg.MSG_GET_SUCCESS);
    }
}
